Convert enumeration to string

Posted by emptyheaded on Stack Overflow See other posts from Stack Overflow or by emptyheaded
Published on 2012-04-13T17:20:51Z Indexed on 2012/04/13 17:30 UTC
Read the original article Hit count: 200

Filed under:
|
|
|

I am trying to build a function that converts an item from an enum to its corresponding string. The enums I use are fairly long, so I didn't want to use a switch-case. I found a method using boost::unordered_map very convenient, but I don't know how to make a default return (when there is no item matching the enum).

const boost::unordered_map<enum_type, const std::string> enumToString = boost::assign::map_list_of
(data_1, "data_1")
(data_2, "data_2");

I tried to create an additional function:

std::string convert(enum_type entry)
{
    if (enumToString.find(entry))       // not sure what test to place here, 
        return enumToString.at(entry);  //because the find method returns an iter
    else
        return "invalid_value";
}

I even tried something exceedingly wrong:

std::string convert(enum_type entry)
{
    try{
        return enumToString.at(entry);
    }
    catch(...){
        return "invalid_value";
    }
}

Result: evil "Debug" runtime error. Can somebody give me a suggestion on how to either
1) find an easier method to convert enum to a string with the same name as the enum item
2) find a way to use already built boost methods to get a default value from a hash map (best option)
3) find what to place in the test to use a function that returns either the pair of the key-value, or a different string if the key is not found in the map.
Thank you very much.

© Stack Overflow or respective owner

Related posts about c++

Related posts about boost