c++ - 专用模板根据变量类型返回/设置枚举值

标签 c++ templates enums c++14

如果我有一个枚举定义为...

enum MyValue
{
  Unk,
  A,
  B
};

我想创建一个专门的模板,根据变量类型本身返回/设置类型

template<typename T>
struct get_value
{
  // the 'value' should be MyValue::Unk 
};

template<>
struct get_value<int>
{
  // the 'value' should be MyValue::A 
};

template<>
struct get_value<double>
{
  // the 'value' should be MyValue::B 
};

这样我就可以调用结构

auto x = get_value<char>::value; // == MyValue::Unk

auto y = get_value<int>::value; // == MyValue::A

这在c++中是否可能,如果可以,如何实现?

最佳答案

具有以下内容:

template<typename T>
struct get_value
{
  static constexpr MyValue value = MyValue::Unk;
};

template<>
struct get_value<int>
{
  static constexpr MyValue value = MyValue::A;
};

template<>
struct get_value<double>
{
  static constexpr MyValue value = MyValue::B;
};

Demo

关于c++ - 专用模板根据变量类型返回/设置枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39062770/

相关文章:

c++ - 在带有 mingw64 的 Visual Studio Code 中找不到 #include <iostream>

c++ - sprintf 中 Windows 与基于 Unix 的系统的舍入差异

c++ - 为什么C++在对Foo <T>::Foo(T &&)的调用中不能推断T?

c# - 如何从字符串输入中获取显示枚举值

c - 当可以离开编译器设置时,为什么要显式设置枚举的值?

c++ - int `*p = new int(5);` 和 `int *p = new int[5];` 有什么区别

c++ - 在 C++ 中模拟 if __name__ == __main__ 导致错误 "function-like macro is not defined"

c++ - 模板化类然后重载运算符 (C++)

c++ - 在回溯中格式化 GDB 模板参数

java - 如何在Enum中实例化内部类?