Suppose we have some named enums:
enum MyEnum {
FOO,
BAR = 0x50
};
What I googled for is a script (any language) that scans all
Interesting to see the number of ways. here's one i used a long time ago:
in file myenummap.h:
#include
in main.cpp
#include "myenummap.h"
...
mymap nummap;
std::cout<< nummap[ one ] << std::endl;
Its not const, but its convenient.
Here's another way that uses C++11 features. This is const, doesn't inherit an STL container and is a little tidier:
#include
#include
#include
#include
//These stay together and must be modified together
enum test{ one, two, three, five=5, six, seven };
std::string enum_to_str(test const& e)
{
typedef std::pair mapping;
auto m = [](test const& e,std::string const& s){return mapping(static_cast(e),s);};
std::vector const nummap =
{
m(one,"one"),
m(two,"two"),
m(three,"three"),
m(five,"five"),
m(six,"six"),
m(seven,"seven"),
};
for(auto i : nummap)
{
if(i.first==static_cast(e))
{
return i.second;
}
}
return "";
}
int main()
{
// std::cout<< enum_to_str( 46 ) << std::endl; //compilation will fail
std::cout<< "Invalid enum to string : [" << enum_to_str( test(46) ) << "]"<