C++: Parse enums and convert them to other types elegantly
Spanish version / Versión en Español Quite often, we need to to read a value from some source (file, socket, database) and convert it to an enum. In order to define the conversion in a single place, in C++, we usually define a function like this one: enum MyEnum{ VALUE_A, VALUE_B, VALUE_C }; MyEnum ParseMyEnum( const std::string& sMyEnum ){ //Conversion } But where do we define this function? Our first idea is to make it a private method of the class which uses the enum, but this is not possible if the enum is used by more than one class. In those cases, we have no choice but to define the function as a free function inside a namespace. C#'s enums can have methods and extension methods, which would be the most natural and object oriented solution. Nevertheless, since we're talking C++ now, we can use templates to solve this problem in a generic way, for every enum, and use template specialization to define the specific mapping for each enum. This can be ...