Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

resolve enum class variable name

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading