是否可以通过以下方式在运行时使用模板参数实例化一个类?:
#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();
}
所以类SolverA
并SolverB
没有模板参数,但不能在编译时决定使用哪一个。我尝试使用boost::any
它,但我不确定如何转换变量solver
来调用函数calc()
。还有其他想法吗?