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

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

    Note that your conversion function should ideally be returning a const char *.

    If you can afford to put your enums in their separate header files, you could perhaps do something like this with macros (oh, this will be ugly):

    #include "enum_def.h"
    #include "colour.h"
    #include "enum_conv.h"
    #include "colour.h"
    

    Where enum_def.h has:

    #undef ENUM_START
    #undef ENUM_ADD
    #undef ENUM_END
    #define ENUM_START(NAME) enum NAME {
    #define ENUM_ADD(NAME, VALUE) NAME = VALUE,
    #define ENUM_END };
    

    And enum_conv.h has:

    #undef ENUM_START
    #undef ENUM_ADD
    #undef ENUM_END
    #define ENUM_START(NAME) const char *##NAME##_to_string(NAME val) { switch (val) {
    #define ENUM_ADD(NAME, VALUE) case NAME: return #NAME;
    #define ENUM_END default: return "Invalid value"; } }
    

    And finally, colour.h has:

    ENUM_START(colour)
    ENUM_ADD(red,   0xff0000)
    ENUM_ADD(green, 0x00ff00)
    ENUM_ADD(blue,  0x0000ff)
    ENUM_END
    

    And you can use the conversion function as:

    printf("%s", colour_to_string(colour::red));
    

    This is ugly, but it's the only way (at the preprocessor level) that lets you define your enum just in a single place in your code. Your code is therefore not prone to errors due to modifications to the enum. Your enum definition and the conversion function will always be in sync. However, I repeat, this is ugly :)

提交回复
热议问题