【发布时间】:2015-07-21 12:01:06
【问题描述】:
我知道 c++ 模板,它允许您为多种类型编写代码,但是如果我想动态存储和访问一个类型怎么办?为什么这在 C++ 中这么难做?
我非常希望不必须这样做:
enum SupportedTypes
{
IntType,
FloatType,
StringType
}
template <typename T>
class ClassThing
{
public:
T Value;
SupportedTypes Type;
}
...
//Not sure if you could even access thing->Type, but regardless, you get the idea...
switch (thing->Type)
{
case IntType:
DoSomething(((ClassThing<int>*)thing)->T);
break;
case FloatType:
DoSomething(((ClassThing<float>*)thing)->T);
break;
case StringType:
DoSomething(((ClassThing<string>*)thing)->T);
break;
}
为什么 c++ 不支持这样的东西:
int whatIsThis = 5;
type t = typeid(whatIsThis); //typeid exists, but you can't do...:
t anotherInt = 5;
?
另一个我比较乐观的问题是:如果您选择采用模板化路线,如果您将其一般存储在集合中,是否有任何方法可以维护该类型?例如:
vector<ClassThing> things;
(顺便说一句,这将给出“类模板的参数列表...丢失”错误。)我的猜测是,不,这是不可能的,因为上述是不可能的。
【问题讨论】:
标签: c++ templates dynamic types store