There is no way to do that in C++11 or C++14. However, you should consider having some enum class, then code some explicit functions or operators to convert it from and to std::string
-s.
There is a class in C++11 known as enum class which you can store variables inside.
That phrasing is not correct: an enum class does not store variables (but enumerators).
So you might code:
enum class MyEnum : char {
v1 = 'x', v2 = 'y'
};
(this is possible, as answered by druckermanly, because char
is an integral type; of course you cannot use strings instead)
then define some MyEnum string_to_MyEnum(const std::string&);
function (it probably would throw some exception if the argument is an unexpected string) and another std::string MyEnum_to_string(MyEnum);
one. You might even consider also having some cast operator calling them (but I don't find that readable, in your case). You could also define a class MyEnumValue
containing one single data member of MyEnum
type and have that class having cast operator, e.g.
class MyEnumValue {
const MyEnum en;
public:
MyEnumValue(MyEnum e) : en(e) {};
MyEnumValue(const std::string&s)
: MyEnumValue(string_to_MyEnum(s)) {};
operator std::string () const { return MyEnum_to_string(en);};
operator MyEnum () const { return en };
//// etc....
};
With appropriate more things in MyEnumValue
(see the rule of five) you might almost always use MyEnumValue
instead of MyEnum
(which perhaps might even be internal to class MyEnumValue
)