Home > Mobile >  C template specialization for enum
C template specialization for enum

Time:07-06

I want to map known type to enum value defined by myself.

enum class MyType : uint8_t {
    Int8,
    Uint8,
    Int16,
    Uint16,
    Int32,
    Uint32,
    ... // some other primitive types.
};

template <typename T>
constexpr uint8_t DeclTypeTrait();

template <>
constexpr uint8_t DeclTypeTrait<int8_t>() {
  return static_cast<uint8_t>(MyType::Int8);
}
... // Specialize for each known number type.

Also for any enum type defined by user, I want to map it to Int32. User must define his enum class on int32_t.

using Enumeration = int32_t;

// Some user defined enum.
enum class CameraKind : Enumeration { 
    Perspective, 
    Orthographic 
};

So I implement DeclTypeTrait like this:

template <typename T,
          class = typename std::enable_if<std::is_enum<T>::value>::type>
constexpr uint8_t DeclTypeTrait() {
  return static_cast<uint8_t>(MyType::Int32);
}

But I got error: "call to 'DeclTypeTrait' is ambiguous"

candidate function [with T = CameraKind]
candidate function [with T = CameraKind, $1 = void]

My question is how to accomplish this:

// If a have a variable of known types or any enum on int32.
int8_t v1;
CameraKind camera;
std::string s;

DeclTypeTrait<decltype(v1)>() -> MyType::Int8
DeclTypeTrait<decltype(camera)>() -> MyType::Int32
DeclTypeTrait<decltype(s)>() // Report compile error is OK.

CodePudding user response:

Use a class template will be much simpler for your case.

template <typename T, typename = std::void_t<>>
struct DeclTypeTraitT {
};

template <typename T>
inline constexpr uint8_t DeclTypeTrait = DeclTypeTraitT<T>::value;

template <>
struct DeclTypeTraitT<int8_t> {
    static constexpr uint8_t value = static_cast<uint8_t>(MyType::Int8);
};

template <typename T>
struct DeclTypeTraitT<T, std::enable_if_t<std::is_enum_v<T>>> {
    static constexpr uint8_t value = static_cast<uint8_t>(MyType::Int32);
};

Then

CameraKind camera;
static_assert(DeclTypeTrait<decltype(camera)> == static_cast<uint8_t>(MyType::Int32));

Demo


As @HolyBlackCat saying, if you want to map the underlying type, you can use

template <typename T>
struct DeclTypeTraitT<T, std::enable_if_t<std::is_enum_v<T>>> {
    static constexpr uint8_t value = DeclTypeTrait<std::underlying_type_t<T>>;
};
  • Related