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

前端 未结 7 2187
面向向阳花
面向向阳花 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:05

    It is possible to get your second example (i.e., the one using a scoped enum) to work using the same syntax as unscoped enums. Furthermore, the solution is generic and will work for all scoped enums, versus writing code for each scoped enum (as shown in the answer provided by @ForEveR).

    The solution is to write a generic operator<< function which will work for any scoped enum. The solution employs SFINAE via std::enable_if and is as follows.

    #include <iostream>
    #include <type_traits>
    
    // Scoped enum
    enum class Color
    {
        Red,
        Green,
        Blue
    };
    
    // Unscoped enum
    enum Orientation
    {
        Horizontal,
        Vertical
    };
    
    // Another scoped enum
    enum class ExecStatus
    {
        Idle,
        Started,
        Running
    };
    
    template<typename T>
    std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
    {
        return stream << static_cast<typename std::underlying_type<T>::type>(e);
    }
    
    int main()
    {
        std::cout << Color::Blue << "\n";
        std::cout << Vertical << "\n";
        std::cout << ExecStatus::Running << "\n";
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题