How to know underlying type of class enum?

Since C++ 11 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);

In C++ 14 it has been a bit simplified (note there is no ::type):

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

And finally since C++ 23 one can get value without explicit cast (docs):

auto value = std::to_underlying<FooEnum>(myEnum);

Leave a Comment