mercredi 15 juillet 2020

C++ 11: How to write 2 template functions that differ in their return type

What I'm trying to do is have two function templates: one that translates a string to an boost::optional<some integer type> and one that translates a string to a boost::optional<some enum type>. Something like this:

template<typename T> boost::optional<T> func(const std::string &s) { return boost::make_optional(std::stoi(s));}
template<typename T> boost::optional<T> func(const std::string &s) { return boost::make_optional(EnumMapper<T>::map_string_to_enum<T>(s));}

enum Color { Red, Blue, Green};
enum Direction { Up, Down, Left, Right};

auto a = func<int>("1234");
auto b = func<Color>("red");
auto c = func<Direction>("up");

I have something working where I make specializations for every enum type:

template<> boost::optional<Color> func(const std::string &s) { return boost::make_optional(EnumMapper<Color>::map_string_to_enum<Color>(s));}
template<> boost::optional<Direction> func(const std::string &s) { return boost::make_optional(EnumMapper<Direction>::map_string_to_enum<Direction>(s));}

but with literally dozens of enums this seems ugly and error prone. I have a feeling that this is what type traits are there for, but none of the examples I found seems to work for what I want to do.

Aucun commentaire:

Enregistrer un commentaire