How can I output the value of an enum class
in C++11? In C++03 it\'s like this:
#include
using namespace std;
enum A {
a =
(I'm not allowed to comment yet.) I would suggest the following improvements to the already great answer of James McNellis:
template
constexpr auto as_integer(Enumeration const value)
-> typename std::underlying_type::type
{
static_assert(std::is_enum::value, "parameter is not of type enum or enum class");
return static_cast::type>(value);
}
with
constexpr
: allowing me to use an enum member value as compile-time array sizestatic_assert
+is_enum
: to 'ensure' compile-time that the function does sth. with enumerations only, as suggestedBy the way I'm asking myself: Why should I ever use enum class
when I would like to assign number values to my enum members?! Considering the conversion effort.
Perhaps I would then go back to ordinary enum
as I suggested here: How to use enums as flags in C++?
Yet another (better) flavor of it without static_assert, based on a suggestion of @TobySpeight:
template
constexpr std::enable_if_t::value,
std::underlying_type_t> as_number(const Enumeration value)
{
return static_cast>(value);
}