c++11 outputs the value of enum class in the correct position

  • 2020-11-20 06:11:42
  • OfStack

c++11 has added enum class, which is much more beneficial than traditional enum, but it also has some unpleasant aspects, such as: when output to std stream, it will report an error; if there is a strong turn, there will be no information output. So, how do you get the value of enum class out to std stream?

The reason for offering this enum class is that the old enum had a number of drawbacks. Brief description 1:

1. Easy to be implicitly converted to int

underlying type refers to the implementation details behind the scenes of the compiler implementors that lead to non-conformance across platforms and compilers. The inestimable size and so on.

3. There are no strict scope boundaries

Below, I introduce one way to pass overloading < < The method of the operator is as follows:


#include <iostream>
#include <sstream>

enum class error_code
{
  ok=0,
  invalid_args=1,
  runtime_error=2,
  //..
}; 

// overloading operator<< The operator, make error_code support << The output 
std::ostream & operator<<(std::ostream &os,const error_code &ec)
 {
   os<<static_cast<std::underlying_type<error_code>::type>(ec);
   return os;
 }


using namespace std;

int main(int argc,char *argv[])
{
  cout<<error_code::ok<<endl;
  cout<<error_code::invalid_arg<<endl;
  cout<<error_code::runtime_error<<endl;
 
  stringstream ss;
  ss<<error_code::runtime_error;

  return 0;
}


Related articles: