Can’t use enum class as unordered_map key

I use a functor object to calculate hash of enum class: struct EnumClassHash { template <typename T> std::size_t operator()(T t) const { return static_cast<std::size_t>(t); } }; Now you can use it as 3rd template-parameter of std::unordered_map: enum class MyEnum {}; std::unordered_map<MyEnum, int, EnumClassHash> myMap; So you don’t need to provide a specialization of std::hash, the … Read more

Is it possible to determine the number of elements of a c++ enum class?

Not directly, but you could use the following trick: enum class Example { A, B, C, D, E, Count }; Then the cardinality is available as static_cast<int>(Example::Count). Of course, this only works nicely if you let values of the enum be automatically assigned, starting from 0. If that’s not the case, you can manually assign … Read more

How can I output the value of an enum class in C++11

Unlike an unscoped enumeration, a scoped enumeration is not implicitly convertible to its integer value. You need to explicitly convert it to an integer using a cast: std::cout << static_cast<std::underlying_type<A>::type>(a) << std::endl; You may want to encapsulate the logic into a function template: template <typename Enumeration> auto as_integer(Enumeration const value) -> typename std::underlying_type<Enumeration>::type { return … Read more