Is there a simple way to convert C++ enum to string?

后端 未结 30 2799
我在风中等你
我在风中等你 2020-11-22 10:37

Suppose we have some named enums:

enum MyEnum {
      FOO,
      BAR = 0x50
};

What I googled for is a script (any language) that scans all

30条回答
  •  生来不讨喜
    2020-11-22 11:07

    As variant, use simple lib > http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C

    In the code

    #include 
    
    enum FORM {
        F_NONE = 0,
        F_BOX,
        F_CUBE,
        F_SPHERE,
    };
    

    add lines

    Begin_Enum_String( FORM )
    {
        Enum_String( F_NONE );
        Enum_String( F_BOX );
        Enum_String( F_CUBE );
        Enum_String( F_SPHERE );
    }
    End_Enum_String;
    

    Work fine, if values in enum are not dublicate.

    Example usage

    enum FORM f = ...
    const std::string& str = EnumString< FORM >::From( f );
    

    and vice versa

    assert( EnumString< FORM >::To( f, str ) );
    

提交回复
热议问题