Consider I’ve got the followin enum class:
enum class TestEnum
{
None = 0,
Foo,
Bar
};
I’d like to specify ostream operator ( << ) for this enum class so I could write:
std::cout << "This is " << TestEnum::Foo;
and get following output This is Foo.
My question is:
Is there any place where enum "name specifiers" are stored? (i.e. for enum class TestEnum it is None, Foo and Bar) So I could write a function ( or at best function template ) that specifies ostream operator for this TestEnum like:
std::ostream& operator<< ( std::ostream& os, TestEnum aEnum )
{
return std::string( aEnum.name() );
}
So far I did it this way:
std::ostream& operator<< ( std::ostream& os, TestEnum aEnum )
{
switch( aEnum )
{
case TestEnum::Foo:
os << "Foo";
break;
case TestEnum::Bar:
os << "Bar"
break;
}
return os;
}
I’ve seen some solutions using boost library but I would prefer not using it this time.
>Solution :
Is there any place where enum "name specifiers" are stored?
No, but one option is to use std::map<TestEnum, std::string> as shown below:
enum class TestEnum
{
None = 0,
Foo,
Bar
};
std::map<TestEnum,std::string> myMap{{TestEnum::None, "None"},
{TestEnum::Foo, "Foo"},
{TestEnum::Bar, "Bar"}};
std::ostream& operator<< ( std::ostream& os, TestEnum aEnum )
{
os << myMap.at(aEnum);
return os;
}
int main()
{
std::cout << "This is " << TestEnum::Foo; //prints This is Foo
std::cout << "This is " << TestEnum::Bar; //prints This is Bar
return 0;
}