The title might seem a little confusing, so here is a more thorough explanation:
I have a templated class that has a vector as a member variable. The template argument is a struct (or class) that will have one certain variable. The type of this vector shall be derived from the template argument (from this one certain variable). The tricky part is that it shall be derived from a member variable of the template argument.
#include <vector>
#include <complex>
using namespace std;
struct thingA {
double variable;
//...
};
struct thingB {
complex<double> variable;
//...
};
template <class S>
class someClass {
vector< " type of S::variable " > history; // If S=thingA, make it a double, if S=tingB make it a complex<double>
}
// Usage:
someClass<thingA> myInstanceA; // (this instance should now have a vector<double>)
someClass<thingB> myInstanceB; // (this instance should now have a vector<complex<double>>)
Inheriting from a template classIt is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.
A non-template class can have template member functions, if required. Notice the syntax. Unlike a member function for a template class, a template member function is just like a free template function but scoped to its containing class.
Member function templates are template functions that are members of a class or class template. Member functions can be function templates in several contexts. All functions of class templates are generic but are not referred to as member templates or member function templates.
A member function template cannot be virtual, and a member function template in a derived class cannot override a virtual member function from the base class.
You can get the type via decltype
, if the names of data member are always the same:
template <class S>
class someClass {
vector< decltype(S::variable) > history; // if S=thingA, make it a double, if S=tingB make it a complex<double>
};
I would define the type in the struct
s and use it in the class
:
#include <vector>
#include <complex>
using namespace std;
struct thingA {
using Type = double;
Type variable;
//...
};
struct thingB {
using Type = complex<double>;
Type varbiable;
//...
};
template <class S>
class someClass {
vector<typename S::Type> history; // if S=thingA, make it a double, if S=tingB make it a complex<double>
};
// usage:
someClass<thingA> myInstanceA; // (this instance should now have a vector<double>)
someClass<thingB> myInstanceB; // (this instance should now have a vector<complex<double>>)
https://godbolt.org/z/raE9hbnqW
That is also the way to go when the variables do not have the same name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With