How do I get the fundamental type of an enum?

后端 未结 2 1995
花落未央
花落未央 2021-01-04 10:39

With a declaration such as:

enum DrawBoldMode : unsigned
{
    DBM_NONE =              0,
    DBM_ITEM =              1<<0,   // bold just the nearest          


        
2条回答
  •  天命终不由人
    2021-01-04 11:12

    std::underlying_type is available in GCC 4.7, but until then you can get an approximate emulation with templates:

    #include 
    // This is a hack because GCC 4.6 does not support std::underlying_type yet.
    // A specialization for each enum is preferred
    namespace detail {
        template 
        struct filter;
    
        template 
        struct filter {
            typedef typename std::tuple_element<0, Acc>::type type;
        };
    
        template 
        struct filter, Head, Tail...>
        : std::conditional, Tail...>
                          , filter, Tail...>
                          >::type {};
    
        template 
        struct find_best_match : filter, In...> {};
    }
    
    namespace std {
        template 
        struct underlying_type : detail::find_best_match {};
    }
    

    It doesn't give you the exact type, but it gives you one with the same size and signedness characteristics.

提交回复
热议问题