I have the following redundant-feeling design to convert between enum
s and strings regarding a class that stores enum
s. The approach doesn't scale if there are more enum
s and in any event, less-redundant code is also better.
Questions
If there will be more
enum
s, would it be possible to avoid defining two explicit conversion functions per enum type and device a system where the caller sees just one (i.e. convert) or two different function names (i.e.convertto
/convertfrom
for all theenum
s, not just perenum
type)? Perhaps using some kind deduction magic withauto
anddecltype
? It looks like ambiguity sets in since only the return value can be used to separate the different functions overloads (even if done with function templates).Is the following design of separating the conversion functions and putting them to an anonymous
namespace
good design (I've thought about putting the conversion functions to a file, say conversions.incl and including it)?
The idea would be make the multiple (i.e. more enum
s than the one presented here) conversions as implicit as possible
The conversions would be used like this:
random.cpp
string token_string = "none"; //In reality this will be externally, user, generated.
some_class_instance->set_type(enum_conversion(token_string));
token_string = enum_conversion(some_class_instance->get_type());
And to present one enum
and related conversions (but there could be more):
some_class.h
class some_class
{
public:
enum class enum_type
{
none = 0,
type1 = 1,
type2 = 2
}
void set_type(enum_type);
enum_type get_type() const;
private:
enum_type type_;
};
namespace
{
std::array<std::pair<std::string, some_class::enume_type>, 3> type_map;
bool initialize_map()
{
type_map[0] = std::make_pair("none", some_class::enum_type::none);
type_map[1] = std::make_pair("type1", some_class::enum_type::type1);
type_map[2] = std::make_pair("type2", some_class::enum_type::type2);
}
bool initialization_result = initialize_map();
some_class::enum_type enum_conversion(std::string const& enum_type)
{
for(auto val: type_map)
{
if(val.first == enum_type)
{
return val.second;
}
}
return type_map[0].second;
}
std::string enum_conversion(some_class::enum_type enum_type)
{
for(auto val: type_map)
{
if(val.second == enum_type)
{
return val.first;
}
}
return type_parameter_map[0].first;
}
}