Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ std::enable_if constraint variants and problems

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 "no matching overloaded function found" (VS 2015) error:

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!

like image 751
gilgamash Avatar asked Aug 12 '16 09:08

gilgamash


1 Answers

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 twotemplate parameters and the first can again be deduced but not the second. This is an inappropriate/wrong way to use std::enable_if_t<>.

like image 153
Walter Avatar answered Nov 15 '22 09:11

Walter