Enum class string type in C ++

- reference Information:

In C ++ 11, there is a class known as the enum class, which you can store inside. However, I saw a char class type:

enum class : char {
   v1 = 'x', v2 = 'y'
};

- Question:

Is there any way to express this class of a type string enumeration?

For instance,

enum class : string{
  v1 = "x", v2 = "y"
};

- what I think:

I tried to use it, but I had errors, I'm not sure if I am doing it right or not. The reason I want to use strings is because they are capable of containing multiple characters at the same time, so they make them more useful for my code.

+4
source share
3 answers

++ 11 ++ 14 . , enum class, , std::string -s.

++ 11 , enum, .

: enum ( ).

, :

enum class MyEnum : char {
   v1 = 'x', v2 = 'y'
};

(, druckermanly, char , , )

MyEnum string_to_MyEnum(const std::string&); (, , ) std::string MyEnum_to_string(MyEnum);. , ( ). class MyEnumValue, MyEnum, , ,

 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....
 };

MyEnumValue (. ), MyEnumValue MyEnum (, , class MyEnumValue)

+4

The compiler internally converts your char to its equivalent int (ASCII) representation. Thus, it would be impossible to use a string.

0
source

Source: https://habr.com/ru/post/1675230/