c++reflectionc++20typeid

Map enum values to corresponding types with templates at compile time?


I have an idea of mapping enum values to corresponding data types, at compile time with templates. How can i do this?

e.g.


enum DataType {
  UNSINGED_INT; // uint32_t
  INT; // int32_t
  UNSIGNED_CHAR; // uint8_t
  CHAR; // int8_t
}

auto type = MapToDataType<DataType::UNSIGNED_CHAR>; // type will be uint8_t in this case


Solution

  • Declare the enum class. Use class to avoid namespace pollution.

    #include <cstdint>
    
    enum class DataType {
        UNSIGNED_CHAR,
        UNSIGNED_INT,
        CHAR,
        INT
    };
    

    Specialize a template for each enum entry:

    template <DataType> struct MapToDataType_t;
    template <> struct MapToDataType_t<DataType::UNSIGNED_CHAR> { using type = std::uint8_t; };
    template <> struct MapToDataType_t<DataType::UNSIGNED_INT>  { using type = std::unit32_t; };
    template <> struct MapToDataType_t<DataType::CHAR>          { using type = std::int8_t; };
    template <> struct MapToDataType_t<DataType::INT>           { using type = std::int32_t; };
    

    Alias each type:

    template <DataType T>
    using MapToDataType = typename MapToDataType_t<T>::type;