(I am not yet allowed to comment.) I would suggest the following improvements to James McNellis's already excellent answer:
template <typename Enumeration> constexpr auto as_integer(Enumeration const value) -> typename std::underlying_type<Enumeration>::type { static_assert(std::is_enum<Enumeration>::value, "parameter is not of type enum or enum class"); return static_cast<typename std::underlying_type<Enumeration>::type>(value); }
from
constexpr : allows me to use the value of an enumeration element as the size of a compile-time arraystatic_assert + is_enum : "ensure" the compilation time that the sth function executes. with listings as suggested
By the way, I ask myself: why should I ever use enum class when I would like to assign numerical values ββto my enumeration members ?! Given the conversion effort.
Perhaps I will return to the regular enum , as I suggested here: How to use enums as flags in C ++?
Another (better) taste of this without static_assert, based on @TobySpeight's suggestion:
template <typename Enumeration> constexpr std::enable_if_t<std::is_enum<Enumeration>::value, std::underlying_type_t<Enumeration>> as_number(const Enumeration value) { return static_cast<std::underlying_type_t<Enumeration>>(value); }
yau Nov 07 '14 at 19:57 2014-11-07 19:57
source share