gilgamash - 1 year ago 60

C++ Question

Just a short question given a function where I want to return the underlying type of an

`enum class`

Why does this version work fine

`template<typename T>`

constexpr inline

typename std::enable_if_t<

std::is_enum<T>::value,

typename std::underlying_type_t<T>

>

enumValue(T p_rVal) noexcept

{

return static_cast<typename std::underlying_type_t<T>>(p_rVal);

}

if (enumValue(myEnumClass) == 0) {}

whereas this one fails with a "

`template<`

typename T,

typename std::enable_if_t<

std::is_enum<T>::value,

typename std::underlying_type_t<T>

>

>

constexpr inline

typename std::underlying_type_t<T>

enumValue(T p_rVal) noexcept

{

return static_cast<typename std::underlying_type_t<T>>(p_rVal);

}

Thanks a lot for help!

Answer Source

In your first example, there is only one `template`

parameter, `T`

, which in the function call `enumValue(myEnumClass)`

is deduced from the argument. This is the correct usage of `std::enable_if_t<>`

.

In your second example, there are two`template`

parameters and the first can again be deduced but not the second. This is an inappropriate/wrong way to use `std::enable_if_t<>`

.