Since I have been using templates in C++, I often encounter this problem: I would like to gather instances of different versions of a templated class in a vector.
I unde
If you want to store different template classes, you can make a parent class and inherit that class in the template class.
And I don't know why you're using switch
for types, just use template instantiation.
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
class Mother {
public:
virtual void doSomeThing() = 0;
};
template<typename T>
class Child : public Mother {
void doSomeThing() override;
};
template<typename T> void Child<T>::doSomeThing() {
cout << "Base Function" << endl;
}
template<> void Child<int>::doSomeThing() {
cout << "Int template" << endl;
}
template<> void Child<float>::doSomeThing() {
cout << "Float template" << endl;
}
int main() {
std::vector<std::unique_ptr<Mother>> vec;
vec.emplace_back(new Child<double>());
vec.emplace_back(new Child<int>());
vec.emplace_back(new Child<float>());
vec[0]->doSomeThing();
vec[1]->doSomeThing();
vec[2]->doSomeThing();
return 0;
}
output:
Base Function
Int template
Float template
Process finished with exit code 0