Home > database >  How to use multiple conditions in enable_if?
How to use multiple conditions in enable_if?

Time:04-15

I have the following code:

#include <iostream>
#include<type_traits>
using namespace std;

enum class a : uint16_t
{
    x, y
};
template<typename T>
using isUint16ScopedEnum = std::integral_constant<
  bool,
  std::is_enum_v<T> && std::is_same_v<std::underlying_type_t<T>, uint16_t> && !std::is_convertible_v<T, uint16_t>>;

template<typename T, std::enable_if_t<is_same_v<T, uint16_t>, void**> = nullptr>
void f(T t)
{
    cout << "works\n";
}

template<typename T, std::enable_if_t<isUint16ScopedEnum<T>::value, void**> = nullptr>
void g(T t)
{
    cout << "also works\n";
}

template<typename T, std::enable_if_t<isUint16ScopedEnum<T>::value || is_same_v<T, uint16_t>, void**> = nullptr>
void h(T t)
{
    cout << "Works with enum, Fails with uint\n";
}

int main()
{
    a A = a::x;
    f((uint16_t)1);
    g(A);
    h(A);
    //h((uint16_t)1);
}

The commented line in main doesn't work and I can't figure out why. If I pass an uint16_t to h, shouldn't the second condition enable the template? The compiler keeps complaining that it is not an enum... Why is it failing to instantiate h(uint16_t)?

CodePudding user response:

(uint16_t)1 is of type uint16_t and not an enum type, so there is no member type for underlying_type, which causes underlying_type_t to be ill-formed and aborts compilation.

You can wrap is_enum_v<T> && is_same_v<underlying_type_t<T>, ...> into a separate trait and use partial specialization to apply underlying_type_t to T only when T is enum type, e.g.

template<typename E, class T, bool = std::is_enum_v<E>>
struct underlying_type_same_as;

template<typename E, class T>
struct underlying_type_same_as<E, T, false> : std::false_type { };

template<typename E, class T>
struct underlying_type_same_as<E, T, true>
 : std::is_same<std::underlying_type_t<E>, T> { };

Then isUint16ScopedEnum can be rewritten as

template<typename T>
using isUint16ScopedEnum = std::bool_constant<
  underlying_type_same_as<T, uint16_t>::value && !std::is_convertible_v<T, uint16_t>>;

Demo

  • Related