Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know underlying type of class enum?

Tags:

c++

c++11

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?

like image 315
Kyle Avatar asked Feb 18 '12 17:02

Kyle


2 Answers

You can use this:

  • std::underlying_type class template to know the underlying type of enum.

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); 
like image 173
Nawaz Avatar answered Sep 30 '22 19:09

Nawaz


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; } 
like image 25
Howard Hinnant Avatar answered Sep 30 '22 18:09

Howard Hinnant