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

前端 未结 7 2265
面向向阳花
面向向阳花 2020-11-30 19:00

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 =          


        
7条回答
  •  抹茶落季
    2020-11-30 20:04

    (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 size
    • static_assert+is_enum: to 'ensure' compile-time that the function does sth. with enumerations only, as suggested

    By 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);
    }
    

提交回复
热议问题