本文介绍了动态模板实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类模板,我需要声明该类的对象,而无需定义类型参数,以便稍后可以有条件地定义它们,例如:
I've got a class template, and I need to declare an object of that class, without defining the type parameters, so that I can define them conditionally later, e.g.:
template<typename T> class A{ public: A(T v){var = v}; ~A(){}; T var; } int main(){ A<>* object; // Or sometihng along these lines...? if(/* something*/) object = new A<float>(0.2f); else{ object = new A<int>(3); } }推荐答案
,您当然无法做到。您必须使A衍生自另一个类,例如:
Well, you certainly can't do that. You'll have to make A derive from another class, for example:
template<typename T> class A : public B { public: A(T v){var = v}; ~A(){}; T var; } int main(){ B* object; if(/* something*/) object = new A<float>(0.2f); else{ object = new A<int>(3); } }更多推荐
动态模板实例化
发布评论