Tre*_*key 6 c++ enums class function c++11
这是一些枚举类:
enum class Race : char {AINU, ELF, DWARF, MAN, EAGLE, HOBBIT, ENT, ORC, WIZARD};
enum class Color: char {RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE};
enum class Direction: char{UP, DOWN, LEFT, RIGHT};
我想为每个实现一个enum_to_string函数和一个string_to_enum函数.
将枚举转换为字符串没有问题,因为我可以重载相同的函数名称.  
std::string to_string(Race const& enum_value);
std::string to_string(Color const& enum_value);
std::string to_string(Direction const& enum_value);
但是,转换为枚举时,不能以相同的方式重载,因为只有返回类型才会不同.(我也不想,因为不同的枚举可以用相同的字符串表示.)
将字符串转换为枚举可以使用以下方法之一吗?
Race race = to_enum<Race>("elf");
Color color = to_enum<Color>("green");
std::string blah{"up"};
Direction dir{to_enum<Direction>(blah)};
或者可能:
Race race = to_enum(Race,"elf");
Color color = to_enum(Color,"green");
std::string blah{"up"};
Direction dir{to_enum(Direction,blah)};
C++可以支持这些行为中的一个或两个吗?
我试图避免像这样的不同函数名称:
Race to_race(std::string const& str);
Color to_color(std::string const& str);
Direction to_direction(std::string const& str);  
这是我能想到的最接近的事情,
template <typename T>struct to_enum{};
template <>
struct to_enum<Color>{
    static Color convert(std::string const& str){
        //match the string with a color enum, and return that color enum
        //(or like a default color enum if the string is garbage or something)
    }
};
然后你这样称呼它:
Color color = to_enum<Color>::convert("red");
我们可以摆脱皈依者吗?或者可能实施这个?
Color color = to_enum(Color,"red");
使用功能模板和专业化.在极少数情况下,我认为功能专业化确实有帮助.
template<typename TEnum>
TEnum enum_cast(std::string const & s);
然后专门为每个枚举类型.我改了名字,所以你可以像演员一样读它:
Color color = enum_cast<Color>("blue");
或者parse也是一个好名字.选择你认为好的任何东西.我个人会选择parse或者enum_cast.
现在to_string,您可以定义重载(您已经拥有):
std::string to_string(Color c);
std::string to_string(Race r);
std::string to_string(Direction d);
不要使用模板和专业化to_string.一般来说,超载确实很好.