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

前端 未结 7 2318
面向向阳花
面向向阳花 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 19:53

    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::type>(a) << std::endl;
    

    You may want to encapsulate the logic into a function template:

    template 
    auto as_integer(Enumeration const value)
        -> typename std::underlying_type::type
    {
        return static_cast::type>(value);
    }
    

    used as:

    std::cout << as_integer(a) << std::endl;
    

提交回复
热议问题