Say you have a template named MyTemplatedClass
and you want to store multiple specialisations of the template inside a vector
:
template<typename T>
class MyTemplatedClass {
public:
void print();
}
std::vector<MyTemplatedClass*> myVector; // <--- won't compile!
As a first solution we could add more vectors, one for every template specialisations, even though it would work at a small scale, as soon as you begin to have more and more speacializations, it's a no-go.
Another solution would be for you to have a non-templated base class in which the template would extend.
// it's not a template!
class MyBaseClass {
public:
virtual void print() = 0; // pure-virtual
};
// MyTemplatedClass extends MyBaseClass
template<typename T>
class MyTemplatedClass : public MyBaseClass {
private:
T value;
public:
MyTemplatedClass(T value) : value(value) {};
virtual void print() {
std::cout << value << std::endl;
}
};
std::vector<MyBaseClass*> myVector; // <--- this will compile! Great!
Great! Problem solved! If you don't believe me check this Ideone