根据 std::is_same 中的枚举值检查模板参数

111*_*001 1 c++ templates c++14

考虑以下:

enum color {
    r, g, b 
};

template <color T>
constexpr bool is_green = std::is_same<T, color::g>::value; 
Run Code Online (Sandbox Code Playgroud)

g++ 无法编译它,出现错误

错误:模板参数列表中参数 1 处的类型/值不匹配 template<class, class> struct std::is_same

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

template <color foo>
class widget
Run Code Online (Sandbox Code Playgroud)

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

son*_*yao 5

std::is_same比较类型,而不是。您可以仅用于==比较值。例如

template <color T>
constexpr bool is_green = T == color::g; 
Run Code Online (Sandbox Code Playgroud)

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

是的你可以。但请注意,它是非类型模板参数,而不是类型模板参数