If I have a template class, that I want to instantiate with different data types:
template <typename T>
class A {
T value;
// ...
};
And I also want to use the objects of this class in a Standard Template Library container (say vector
).
In my understanding creating a vector of A
objects would not be accepted by the compiler, because A<int>
and A<char>
are actually different types and I can't put them in the same vector.
The workaround I found was creating a base class, a derived template class, and a vector of base class pointers.
class ABase {
// ...
};
template <typename T>
class ADerived : public ABase{
T value;
// ...
};
std::vector<BaseA*> mySuperVector;
I am starting to experiment with templates to gain a better understanding and I am wondering whether there are better solutions for this. My workaround above gives me also headache, because I am afraid that typecasting will be inevitable at some point.