简体   繁体   English

带有模板类的c ++中的多态性

[英]Polymorphism in c++ with templated classes

I would like to use a templated class in c++ with one of the template argument determined by user input in run-time. 我想在c ++中使用模板化类,其中一个模板参数由运行时用户输入确定。 I am pretty sure there is an easy and nice way to do it but I am quite new to c++ and I am still struggling with polymorphism and template classes... 我很确定有一种简单而好的方法可以做到这一点,但我对c ++很新,而且我仍在努力处理多态和模板类...

Here is what I would like to do: 这是我想做的事情:

if (argument==0)
      typedef Class1 ActualClassUsed;
if (argument==1)
      typedef Class2 ActualClassUsed;

MyTemplatedClass<ActualClassUsed> * object= MyTemplatedClass<ActualClassUsed>::New();

obviously in the example above ActualClassUsed is not defined in the proper scope... Any easy way to correct this ? 显然在上面的例子中,在正确的范围内没有定义ActualClassUsed ...任何简单的方法来纠正这个?

Thanks for your help ! 谢谢你的帮助 !

Templates is actually duplicating the same code with corresponding data( needed data types only ,not all ) types.That is actually happens at compile time. 模板实际上是使用相应的数据( 仅需要数据类型,而不是所有类型 )复制相同的代码。这实际上是在编译时发生的。

Templates is useful when different data type's (either user defined or built in data types) process in the same way 当不同的数据类型(用户定义或内置数据类型)以相同的方式处理时,模板很有用

currently it is not possible to instantiate template at run-time. 目前无法在运行时实例化模板。

I would like to use a templated class in c++ with one of the template argument determined by user input in run-time. 我想在c ++中使用模板化类,其中一个模板参数由运行时用户输入确定。 I am pretty sure there is an easy and nice way to do it 我很确定有一种简单而好的方法可以做到这一点

Nope there isn't. 不,没有。 It's actually fundamentally impossible by design. 实际上,设计根本不可能。

Templates are a developer tool which generates code the moment you compile your program, which hopefully happens before it is run by any user, time travel aside it is pretty hard to use an information before someone gave it to you. 模板是一个开发人员工具,它在您编译程序的那一刻生成代码,希望任何用户运行之前发生,时间旅行除了在某人提供给您之前很难使用信息。

You can't decide on a fixed color for the car you're building in your factory based on which day the futur driver is going to use it. 根据未来司机将要使用它的日期,您无法决定您在工厂中建造的汽车的固定颜色。 If you want something like that it has to be a dynamic chameleon like color which changes based on the day. 如果你想要这样的东西,它必须是一个动态的变色龙,如颜色,根据一天的变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM