【问题标题】:Specialised template return/set an enum value based on the variable type专用模板根据变量类型返回/设置枚举值
【发布时间】:2016-08-21 09:28:46
【问题描述】:

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

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++中是否可以,如果可以,如何实现?

【问题讨论】:

    标签: c++ templates enums c++14


    【解决方案1】:

    以下内容:

    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

    【讨论】:

      【解决方案2】:

      C++14 新增Variable templates,你也可以使用:

      namespace get_value {
          template<typename T>
          constexpr MyValue value = MyValue::Unk;
      
          template<>
          constexpr MyValue value<int> = MyValue::A;
      
          template<>
          constexpr MyValue value<double> = MyValue::B;
      }
      

      不过,它们的用法有点不同:

      int main() {
          std::cout << get_value::value<char> << std::endl;
          std::cout << get_value::value<int> << std::endl;
          std::cout << get_value::value<double> << std::endl;
      }
      

      【讨论】:

      • 这很好用,我想这是风格/品味的问题,但在这种情况下,我更喜欢另一种方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2023-03-28
      • 2023-03-31
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多