【发布时间】:2012-12-28 13:54:09
【问题描述】:
这里有一些枚举类:
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");
【问题讨论】:
-
你可以避免
Race race = to_enum<Race>("elf");中的冗余(例如)使用auto来避免重复类型:auto race = to_enum<Race>("elf");。
标签: c++ class function c++11 enums