Is it possible to instantiate a class with a template parameter at runtime in the following way?:
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
struct Foo {
vector<T> d;
};
template<typename T>
struct Solver {
Foo<T> data;
virtual void calc() = 0;
};
struct SolverA : Solver<int>
{
void calc()
{
cout << "PRINT A\n";
}
};
struct SolverB : Solver<double>
{
void calc()
{
cout << "PRINT B\n";
}
};
int main()
{
... solver;
if (...) {
solver = new SolverA;
} else {
solver = new SolverB;
}
solver->calc();
}
So classes SolverA and SolverB has no template parameter, but which one just be used cannot be decide at compile time. I tried to used boost::any for this, but I was not sure how to cast than the variable solver to call the function calc(). Any other ideas?
Add a interface for your class :
Templates and virtual dispatch do not go along.