使用字符串声明变量类型

Declare a variable type using a string

本文关键字:变量 类型 声明 字符串      更新时间:2023-10-16

我有一个模板,我想用合适的对象类型调用它,而不必解析字符串标识符/enum/typeid.name()等。

也就是说,而不是:

switch(varType)
{
case TYPE_ONE:
    templateFunction<TYPE_ONE>();
    break;
case TYPE_TWO:
    templateFunction<TYPE_TWO>();
    break;
...
etc...
}

我更喜欢使用:

templateFunction<GetTypeFromEnum(MyEnum::INT)>();

或者更好:

templateFunction<GetTypeFromString("int")>();

有点像倒过来的打字?

事实上,我曾经在VBA中做到过这一点,所以我认为它在C++中一定是可行的。。。

你能重新定义你的templateFunction吗?

template <typename T>
void templateFunction(const T& Dummy)
{
  // Do nothing with Dummy
}

这样做,您只需要将变量varType传递给您调用函数的位置:

templateFunction(varType);