How to know underlying type of class enum?

前端 未结 4 994
温柔的废话
温柔的废话 2020-12-03 17:05

I have a variable declared as:

enum class FooEnum: uint64_t {}

and I would like to cast to its base-type, but I don\'t want to hardcode the

4条回答
  •  鱼传尺愫
    2020-12-03 17:06

    Here is another approach for when underlying_type is not present. This method doesn't attempt to detect the signed-ness of the enum, just give you a type of the same size, which is more than enough for a lot of situations.

    template
    class TIntegerForSize
    {
        typedef void type;
    };
    
    template<>
    struct TIntegerForSize<1>
    {
        typedef uint8_t type;
    };
    
    template<>
    struct TIntegerForSize<2>
    {
        typedef uint16_t type;
    };
    
    template<>
    struct TIntegerForSize<4>
    {
        typedef uint32_t type;
    };
    
    template<>
    struct TIntegerForSize<8>
    {
        typedef uint64_t type;
    };
    
    template
    struct TIntegerForEnum
    {
        typedef typename TIntegerForSize::type type;
    };
    

    Usage:

    enum EFoo {Alpha, Beta};
    EFoo f = Alpha;
    TIntegerForEnum::type i = f;
    TIntegerForEnum::type j = f;
    

提交回复
热议问题