动态模板实例化

编程入门 行业动态 更新时间:2024-10-23 14:34:40
本文介绍了动态模板实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个类模板,我需要声明该类的对象,而无需定义类型参数,以便稍后可以有条件地定义它们,例如:

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); } }

更多推荐

动态模板实例化

本文发布于:2023-08-04 17:37:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298282.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   模板   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!