考虑以下模板类
class MyClassInterface {
public:
virtual double foo(double) = 0;
}
class MyClass<int P1, int P2, int P3>
: public MyClassInterface {
public:
double foo(double a) {
// complex computation dependent on P1, P2, P3
}
// more methods and fields (dependent on P1, P2, P3)
}
Run Code Online (Sandbox Code Playgroud)
模板参数P1,P2,P3是在限制范围就像从0一些固定值n固定在编译时.
现在我想建立一个像"工厂"的方法
MyClassInterface* Factor(int p1, int p2, int p3) {
return new MyClass<p1,p2,p3>(); // <- how to do this?
}
Run Code Online (Sandbox Code Playgroud)
问题是如何在模板参数仅在运行时知道时如何实现模板类的构造.对于具有非常大的域(如双)的模板参数,同样可能吗?如果可能的解决方案可扩展到使用更多模板参数,请另请考虑.