Reputation: 401
- Background Information:
There is a class in C++11 known as enum class which you can store variables inside. However, I have only seen the type of the class to be char:
enum class : char {
v1 = 'x', v2 = 'y'
};
- Question:
Is there any way I can express this enum class of type string?
For example,
enum class : string{
v1 = "x", v2 = "y"
};
- What I think:
I tried using it, but I got errors, I am not sure if I am doing it right or not. The reason why I want to use strings is that they are capable of holding multiple characters at the same time, so it makes them more useful for my code.
Upvotes: 21
Views: 47396
Reputation: 1
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
)
Upvotes: 12
Reputation: 1487
Compiler internally converts your char to its equivalent int representation (ASCII). So it would not be possible to use string instead.
Upvotes: 1
Reputation: 2741
No, this is not possible.
http://en.cppreference.com/w/cpp/language/enum states:
The values of the constants are values of an integral type known as the underlying type of the enumeration.
The key point being "integral type" -- a string is not an integral type.
Upvotes: 6