我们来看看这种代码:
// 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
?
如果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");
您可以使用
decltype
关键字:
dword t = GetValueTypeNo<int>();
int test5 = myVector.GetValue<decltype(t)>("test5");
但是这里的模板参数GetValue
将是 dword 而不是 int。