Creating a string list and an enum list from a C++ macro

后端 未结 8 1290
误落风尘
误落风尘 2020-12-14 08:26

In order to make my code shorter and easier to change I want to replace something like

enum{ E_AAA, E_BBB, E_CCC };
static const char *strings{\"AAA\", \"BBB         


        
8条回答
  •  萌比男神i
    2020-12-14 09:07

    Here is a solution with Boost.Preprocessor:

    #include 
    
    #define DEFINE_ENUM_DECL_VAL(r, name, val) BOOST_PP_CAT(name, BOOST_PP_CAT(_, val))
    #define DEFINE_ENUM_VAL_STR(r, name, val) BOOST_PP_STRINGIZE(val)
    #define DEFINE_ENUM(name, val_seq)                                                 \
      enum name {                                                                      \
        BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(DEFINE_ENUM_DECL_VAL, name, val_seq)) \
      };                                                                               \
      static const char* BOOST_PP_CAT(name, _strings[] = ) {                           \
        BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(DEFINE_ENUM_VAL_STR, name, val_seq)) \
      };
    
    DEFINE_ENUM(E, (AAA)(BBB)(CCC))
    

    (AAA)(BBB)(CCC) is a Boost.Preprocessor sequence of tree elements AAA, BBB and CCC; the macro append the enum name to it's modalities:

    enum E { E_AAA, E_BBB, E_CCC };
    static const char* E_strings[] = { "AAA", "BBB", "CCC" };
    

提交回复
热议问题