是否可以将 Dword 转换为类型名称?

is it possible to cast Dword to Type Name?

让我们来看看这种代码:

// Return me Dword of int
dword t = GetValueTypeNo<int>();
//here trying to tell to GetValue that my template is int (since t is dword of int)
int test5 = myVector.GetValue<t>("test5");

当然这种代码是行不通的,实际上是没有用的。但是有可能做那样的事情吗?将 dword 转换为 int 之类的类型名称?

您可以使用 decltype 关键字:

dword t = GetValueTypeNo<int>();
int test5 = myVector.GetValue<decltype(t)>("test5");

但是这里GetValue的模板参数将是dword而不是int。

如果GetValueTypeNo可以做成constexpr函数,你可以做成这样:

template<typename T>
constexpr dword GetValueTypeNo() { ... }

template<dword>
struct Type_selector;

template<>
struct Type_selector<dword_value_for_int> {
    using Type = int;
};

template<>
struct Type_selector<dword_value_for_long> {
    using Type = long;
};

...

template<dword type>
using Type = typename Type_selector<type>::Type;

然后写:

template<dword type>
Type<type> GetValue(...)
{ ... }

constexpr dword t = GetValueTypeNo<int>();
int test5 = myVector.GetValue<t>("test5");