小编And*_*rew的帖子

如何在c ++中动态存储和访问类型?

我知道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;
}
Run Code Online (Sandbox Code Playgroud)

为什么c ++不支持这样的东西:

int whatIsThis = 5;
type t = typeid(whatIsThis); //typeid exists, but you can't do...:
t anotherInt = 5;
Run Code Online (Sandbox Code Playgroud)

我有另一个问题,我对收到一个好的答案更乐观:如果你选择模板化路线,如果你将它存储在一个集合中,有没有办法维护这个类型?例如:

vector<ClassThing> things; …
Run Code Online (Sandbox Code Playgroud)

c++ templates types store dynamic

4
推荐指数
1
解决办法
1475
查看次数

标签 统计

c++ ×1

dynamic ×1

store ×1

templates ×1

types ×1