我可以根据类型ID实现其签名只有不同的模板化函数吗?

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};
Run Code Online (Sandbox Code Playgroud)

我想为每个实现一个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);
Run Code Online (Sandbox Code Playgroud)

但是,转换为枚举时,不能以相同的方式重载,因为只有返回类型才会不同.(我也不想,因为不同的枚举可以用相同的字符串表示.)


将字符串转换为枚举可以使用以下方法之一吗?

Race race = to_enum<Race>("elf");
Color color = to_enum<Color>("green");

std::string blah{"up"};
Direction dir{to_enum<Direction>(blah)};
Run Code Online (Sandbox Code Playgroud)

或者可能:

Race race = to_enum(Race,"elf");
Color color = to_enum(Color,"green");

std::string blah{"up"};
Direction dir{to_enum(Direction,blah)};
Run Code Online (Sandbox Code Playgroud)

C++可以支持这些行为中的一个或两个吗?


我试图避免像这样的不同函数名称:

Race to_race(std::string const& str);
Color to_color(std::string const& str);
Direction to_direction(std::string const& str);  
Run Code Online (Sandbox Code Playgroud)

这是我能想到的最接近的事情,

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)
    }
};
Run Code Online (Sandbox Code Playgroud)

然后你这样称呼它:

Color color = to_enum<Color>::convert("red");
Run Code Online (Sandbox Code Playgroud)

我们可以摆脱皈依者吗?或者可能实施这个?

Color color = to_enum(Color,"red");
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 7

使用功能模板和专业化.在极少数情况下,我认为功能专业化确实有帮助.

template<typename TEnum>
TEnum enum_cast(std::string const & s);
Run Code Online (Sandbox Code Playgroud)

然后专门为每个枚举类型.我改了名字,所以你可以像演员一样读它:

Color color = enum_cast<Color>("blue");
Run Code Online (Sandbox Code Playgroud)

或者parse也是一个好名字.选择你认为好的任何东西.我个人会选择parse或者enum_cast.

现在to_string,您可以定义重载(您已经拥有):

std::string to_string(Color c);
std::string to_string(Race r);
std::string to_string(Direction d);
Run Code Online (Sandbox Code Playgroud)

不要使用模板和专业化to_string.一般来说,超载确实很好.

  • 哦,我,我应该多睡一觉. (2认同)