'Class inheritance with template
I've started learning C++ templates, so I wrote something like the code below. I used a template to make a "generic inheritance". It works, but I haven't found many similar examples, which leads me to believe that this is not a recommendable implementation.
edited
Sorry about the simple example, I will to try to improve this, so I'm writing a linear/nonlinear(extended) Kalman filter, and I'm using templates to define whether the system is linear or nonlinear.
// https://godbolt.org/z/WhdonxY9x
#include <iostream>
#include <vector>
class Linear
{
public:
Linear(){};
void init(){};
void time_update(){};
};
class Nonlinear : public Linear
{
public:
Nonlinear(){};
void loadEq(){};
void applyLinearization(){};
};
template <class Model>
class Filter : public Model
{
public:
Filter(){};
void measurement_update(){};
};
int main(int argc, char **argv)
{
std::vector<double> data{0.3, 0.2, 0.3};
// for nonlinear system
Filter<Nonlinear> nFilter;
for (auto x : data)
{
nFilter.applyLinearization();
nFilter.time_update();
nFilter.measurement_update();
}
// for linear system
Filter<Linear> lFilter;
for (auto x : data)
{
lFilter.time_update();
lFilter.measurement_update();
}
return 0;
}
Solution 1:[1]
Using templates for inheritance is still fine, but there's a point where I wouldn't recommend to do that, especially when it becomes overly complicated with multiple templates to inherit.
Also, as Silvio Mayolo said, it also depends heavily on what you're doing. But generally speaking, I wouldn't say it's frowned upon to add templates for inheritance in C++, at least in my opinion. However, that could maybe change if you could tell us what you're going to use it for exactly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BadUsernameIdea |
