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

后端 未结 30 2611
我在风中等你
我在风中等你 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:09

    I do this with separate side-by-side enum wrapper classes which are generated with macros. There are several advantages:

    • Can generate them for enums I don't define (eg: OS platform header enums)
    • Can incorporate range checking into the wrapper class
    • Can do "smarter" formatting with bit field enums

    The downside, of course, is that I need to duplicate the enum values in the formatter classes, and I don't have any script to generate them. Other than that, though, it seems to work pretty well.

    Here's an example of an enum from my codebase, sans all the framework code which implements the macros and templates, but you can get the idea:

    enum EHelpLocation
    {
        HELP_LOCATION_UNKNOWN   = 0, 
        HELP_LOCAL_FILE         = 1, 
        HELP_HTML_ONLINE        = 2, 
    };
    class CEnumFormatter_EHelpLocation : public CEnumDefaultFormatter< EHelpLocation >
    {
    public:
        static inline CString FormatEnum( EHelpLocation eValue )
        {
            switch ( eValue )
            {
                ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_LOCATION_UNKNOWN );
                ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_LOCAL_FILE );
                ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_HTML_ONLINE );
            default:
                return FormatAsNumber( eValue );
            }
        }
    };
    DECLARE_RANGE_CHECK_CLASS( EHelpLocation, CRangeInfoSequential< HELP_HTML_ONLINE > );
    typedef ESmartEnum< EHelpLocation, HELP_LOCATION_UNKNOWN, CEnumFormatter_EHelpLocation, CRangeInfo_EHelpLocation > SEHelpLocation;
    

    The idea then is instead of using EHelpLocation, you use SEHelpLocation; everything works the same, but you get range checking and a 'Format()' method on the enum variable itself. If you need to format a stand-alone value, you can use CEnumFormatter_EHelpLocation::FormatEnum(...).

    Hope this is helpful. I realize this also doesn't address the original question about a script to actually generate the other class, but I hope the structure helps someone trying to solve the same problem, or write such a script.

提交回复
热议问题