1110101001
1110101001

Reputation: 5097

Checking template parameter against enum value in std::is_same

Consider the following:

enum color {
    r, g, b 
};

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

g++ fails to compile this, erroring with

error: type/value mismatch at argument 1 in template parameter list for template<class, class> struct std::is_same

It's clearly acceptable to declare a templated class using an enum parameter as

template <color foo>
class widget

however, so it seems that it there should be some way to check the value as well (for later use in a conditional; static_if would have been nice but that requires c++17).

Upvotes: 1

Views: 1715

Answers (2)

songyuanyao
songyuanyao

Reputation: 172894

std::is_same compares on types, not values. You can just use == to compare values. e.g.

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

and

It's clearly acceptable to declare a templated class using an enum parameter

Yes you can. But note that it's non-type template parameter, not type template parameter.

Upvotes: 6

Quentin
Quentin

Reputation: 63124

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

I mean... yeah :)

Upvotes: 1

Related Questions