【问题标题】:is it possible to cast Dword to Type Name?是否可以将 Dword 转换为类型名称?
【发布时间】:2019-10-13 16:20:03
【问题描述】:

让我们看看这样的代码:

// 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,每个特化返回一些id和其他模板方法GetValue使用那个id没有任何问题。
  • @VTT 我只是尝试创建一个快速函数来比较 dword 并返回 typedef 或 typename(例如 int),看看是否可行,但似乎 GCC 并不喜欢它^^跨度>
  • 为什么不使用GetValue&lt;int&gt;?为什么需要一定程度的间接性?有什么限制?
  • @Evg 我只是想知道是否可以做类似的事情。
  • 如果GetValueTypeNo可以标记为constexpr,那肯定是可以的。

标签: c++ dword


【解决方案1】:

如果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");

【讨论】:

  • 感谢您的示例,它明确回答了我的问题
【解决方案2】:

您可以使用decltype 关键字:

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

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

【讨论】:

  • 在这种情况下使用 decltype 会破坏这一点,因为不会根据类型号选择模板特化。
猜你喜欢
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
相关资源
最近更新 更多