【问题标题】:Checking template parameter against enum value in std::is_same根据 std::is_same 中的枚举值检查模板参数
【发布时间】:2020-02-28 10:07:53
【问题描述】:

考虑以下几点:

enum color {
    r, g, b 
};

template <color T>
constexpr bool is_green = std::is_same<T, color::g>::value; 

g++ 编译失败,出错

错误:template&lt;class, class&gt; struct std::is_same 模板参数列表中参数 1 的类型/值不匹配

使用枚举参数声明模板类显然是可以接受的

template <color foo>
class widget

但是,因此似乎也应该有某种方法来检查该值(供以后在条件中使用;static_if 本来不错,但需要 c++17)。

【问题讨论】:

  • fwiw std::euqal_to(不要与 std::equal 混淆)比较值,但你不需要它

标签: c++ templates c++14


【解决方案1】:

std::is_same 比较的是类型,而不是。您可以只使用== 来比较值。例如

template <color T>
constexpr bool is_green = T == color::g; 

使用枚举参数声明模板类显然是可以接受的

是的,你可以。但请注意,它是non-type template parameter,而不是type template parameter

【讨论】:

    【解决方案2】:
    template <color T>
    constexpr bool is_green = T == color::g;
    

    我的意思是...是的:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多