How to know underlying type of class enum?

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 base-type. For instance, something like this:

FooEnum myEnum;
uint64_t * intPointer = (underlying_typeof(myEnum))&myEnum;

Is this possible?


You can use this:

The doc says,

Defines a member typedef type of type that is the underlying type for the enumeration T.

So you should be able to do this:

#include <type_traits> //include this

FooEnum myEnum;
auto pointer = static_cast<std::underlying_type<FooEnum>::type*>(&myEnum);

Your guessed syntax is amazingly close. You're looking for std::underlying_type in <type_traits>:

#include <type_traits>
#include <cstdint>

enum class FooEnum: std::uint64_t {};

int main()
    FooEnum myEnum;
    uint64_t* intPointer = (std::underlying_type<FooEnum>::type*)&myEnum;

Both Visual C++ 10.0 and MinGW g++ 4.6.1 lack std::underlying_type, but both accept this code:

template< class TpEnum >
struct UnderlyingType
    typedef typename conditional<
        TpEnum( -1 ) < TpEnum( 0 ),
        typename make_signed< TpEnum >::type,
        typename make_unsigned< TpEnum >::type
        >::type T;

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.

class TIntegerForSize
    typedef void type;

struct TIntegerForSize<1>
    typedef uint8_t type;

struct TIntegerForSize<2>
    typedef uint16_t type;

struct TIntegerForSize<4>
    typedef uint32_t type;

struct TIntegerForSize<8>
    typedef uint64_t type;

template<typename T>
struct TIntegerForEnum
    typedef typename TIntegerForSize<sizeof(T)>::type type;


enum EFoo {Alpha, Beta};
EFoo f = Alpha;
TIntegerForEnum<EFoo>::type i = f;
TIntegerForEnum<decltype(f)>::type j = f;

Need Your Help

jQuery UI Dialog individual CSS styling

jquery css jquery-ui dialog modal-dialog

I'm looking to style a modal dialog (using UI Dialog) with unique CSS that is separate from the traditional dialog, so in essence to have two jQuery dialogs that each look different.

Multiple radio button groups in MVC 4 Razor razor radio-button radio-group

I need to have multiple radio button groups in my form like this: