Home > Enterprise >  type trait with enum as specialisation
type trait with enum as specialisation

Time:06-17

I would like to have a type trait that would be false for any parameter T except for the enum value Http::Get

template<typename T>
  struct isGet : public std::false_type{};

template<>
  struct isGet<Http::Get> : public std::true_type {};

However, it seems that the c compiler does not allow me to specialise a template class with an enum when the first is a typename.

If I instead do :

template<Http T>
  struct isGet : public std::false_type{};

it works!

Any reason why that is the case, and what are the workarounds to achieve what I want.

I basically want the compiler to return the type trait to false even when T is not of a enum type Http

CodePudding user response:

typename and class expect types. Http::Get is (presumably) not a type, but a value, like any other constant (42, 'A', false etc.). And you obviously cannot pass a value when a type is expected.

The solution would be different depending on your use cases. For example:

#include <type_traits>

enum class Http {
    Post,
    Get,
};

template <auto T>
struct isGet : public std::false_type {};

template <>
struct isGet<Http::Get> : public std::true_type {};
  • Related