如何轻松地将C ++枚举映射到字符串


119

我在使用的某些库头文件中有一堆枚举类型,并且我希望有一种将枚举值转换为用户字符串的方法,反之亦然。

RTTI不会为我这样做,因为“用户字符串”必须比枚举更具可读性。

暴力解决方案将是一堆类似这样的功能,但我觉得这有点像C。

enum MyEnum {VAL1, VAL2,VAL3};

String getStringFromEnum(MyEnum e)
{
  switch e
  {
  case VAL1: return "Value 1";
  case VAL2: return "Value 2";
  case VAL1: return "Value 3";
  default: throw Exception("Bad MyEnum");
  }
}

我有一种直觉,认为使用模板是一种优雅的解决方案,但是我还不能完全理解。

更新:感谢您的建议-我应该明确指出枚举是在第三方库标头中定义的,因此我不想更改它们的定义。

我现在的直觉是避免模板并执行以下操作:

char * MyGetValue(int v, char *tmp); // implementation is trivial

#define ENUM_MAP(type, strings) char * getStringValue(const type &T) \
 { \
 return MyGetValue((int)T, strings); \
 }

; enum eee {AA,BB,CC}; - exists in library header file 
; enum fff {DD,GG,HH}; 

ENUM_MAP(eee,"AA|BB|CC")
ENUM_MAP(fff,"DD|GG|HH")

// To use...

    eee e;
    fff f;
    std::cout<< getStringValue(e);
    std::cout<< getStringValue(f);

Answers:


60

如果您希望枚举将自己命名为字符串,请参见这篇文章。否则,a std::map<MyEnum, char const*>会很好地工作。(将字符串文字复制到映射中的std :: strings没有意义)

对于额外的语法糖,这是编写map_init类的方法。目标是允许

std::map<MyEnum, const char*> MyMap;
map_init(MyMap)
    (eValue1, "A")
    (eValue2, "B")
    (eValue3, "C")
;

该函数template <typename T> map_init(T&)返回一个map_init_helper<T>map_init_helper<T>存储T&,并定义琐碎的map_init_helper& operator()(typename T::key_type const&, typename T::value_type const&)。(返回*thisoperator()允许的链接operator(),像operator<<std::ostreamS)

template<typename T> struct map_init_helper
{
    T& data;
    map_init_helper(T& d) : data(d) {}
    map_init_helper& operator() (typename T::key_type const& key, typename T::mapped_type const& value)
    {
        data[key] = value;
        return *this;
    }
};

template<typename T> map_init_helper<T> map_init(T& item)
{
    return map_init_helper<T>(item);
}

由于function和helper类是模板化的,因此可以将它们用于任何地图或类似地图的结构。即它也可以添加条目到std::unordered_map

如果您不喜欢编写这些帮助程序,则boost :: assign提供了相同的功能。


你是正确的提到另一个问题。人们在发布之前应该先看一下“相关问题” ...
xtofl

2
@xtofl:此处显示的“相关问题”与我发布问题时列出的相关问题完全不同!
罗迪

@MSalters,一个std :: map是处理实现的一种有用方法,但是我正在寻找一些减少可能需要的样板代码的方法。
Roddy's

@MSalters,很高兴能够为operator []接受多个参数。但可悲的是,人们无法做到这一点。x [a,b]求和为x [b]。(a,b)表达式使用逗号运算符。因此它等同于您代码中的[“ A”] [“ B”] [“ C”]。您可以将其更改为[eValue1] [“ A”] [eValu ..
Johannes Schaub-litb

函数调用运算符也将是一个很好的选择:map_init(MyMap)(eValue1,“ A”)(eValue2,“ B”)...。那么它等效于boost :: assign:insert(MyMap)(eValue1, “A”)(eValue2, “B”)...(boost.org/doc/libs/1_35_0/libs/assign/doc/index.html
约翰绍布- litb

31

MSalters解决方案是一个很好的解决方案,但基本上是重新实现的boost::assign::map_list_of。如果您有增强功能,则可以直接使用它:

#include <boost/assign/list_of.hpp>
#include <boost/unordered_map.hpp>
#include <iostream>

using boost::assign::map_list_of;

enum eee { AA,BB,CC };

const boost::unordered_map<eee,const char*> eeeToString = map_list_of
    (AA, "AA")
    (BB, "BB")
    (CC, "CC");

int main()
{
    std::cout << " enum AA = " << eeeToString.at(AA) << std::endl;
    return 0;
}

当eeeToString是类的数据成员时,您将如何使用它?我收到“错误:不允许数据成员初始化”
用户

@User:类数据成员是在构造函数中初始化的,通常是在初始化列表中。
MSalters 2012年

有没有办法使所有枚举都可以使用此方法。我有多个枚举声明,并且不希望地图仅适用eee于您的情况下的类型。
贾斯汀·梁

我尝试使用模板,但出现了错误:error: template declaration of 'const boost::unordered::unordered_map<T, const char*> enumToString'
贾斯汀·梁

4
实际上,这个答案在C ++ 11中已经过时了。
Alastair

19

自动从另一表格中生成一种表格。

资源:

enum {
  VALUE1, /* value 1 */
  VALUE2, /* value 2 */
};

产生:

const char* enum2str[] = {
  "value 1", /* VALUE1 */
  "value 2", /* VALUE2 */
};

如果枚举值很大,则生成的表单可以使用unordered_map <>或康斯坦丁建议的模板。

资源:

enum State{
  state0 = 0, /* state 0 */
  state1 = 1, /* state 1 */
  state2 = 2, /* state 2 */
  state3 = 4, /* state 3 */

  state16 = 0x10000, /* state 16 */
};

产生:

template <State n> struct enum2str { static const char * const value; };
template <State n> const char * const enum2str<n>::value = "error";

template <> struct enum2str<state0> { static const char * const value; };
const char * const enum2str<state0>::value = "state 0";

例:

#include <iostream>

int main()
{
  std::cout << enum2str<state16>::value << std::endl;
  return 0;
}

虽然速度最快,但它并不像@MSalters一样容易。
肯尼,

2
如果您有一点perl / python,可以从文本文件中读取字符串列表,并在编译时使用静态char生成.h文件。=“编写程序以编写程序”
马丁·贝克特

@mgb:perl / python并不是几乎任何语言的模板引擎都可以使用的唯一选择(在这种情况下,可以从模板生成两种形式)。
jfs

@jf。是的,重要的一点是在编译时自动构建静态数据表。我可能更喜欢只生成一个哑静态数组。
Martin Beckett

如果在编译时不知道State是否会起作用?我敢肯定,它不会-从理论上讲,编译器必须使用枚举的所有可能值实例化enum2str模板,我敢肯定,gcc(至少)不会这样做。
Alastair 2012年

11

我记得在StackOverflow的其他地方回答过此问题。在这里重复。基本上,这是一个基于可变参数宏的解决方案,并且非常易于使用:

#define AWESOME_MAKE_ENUM(name, ...) enum class name { __VA_ARGS__, __COUNT}; \
inline std::ostream& operator<<(std::ostream& os, name value) { \
std::string enumName = #name; \
std::string str = #__VA_ARGS__; \
int len = str.length(); \
std::vector<std::string> strings; \
std::ostringstream temp; \
for(int i = 0; i < len; i ++) { \
if(isspace(str[i])) continue; \
        else if(str[i] == ',') { \
        strings.push_back(temp.str()); \
        temp.str(std::string());\
        } \
        else temp<< str[i]; \
} \
strings.push_back(temp.str()); \
os << enumName << "::" << strings[static_cast<int>(value)]; \
return os;} 

要在您的代码中使用它,只需执行以下操作:

AWESOME_MAKE_ENUM(Animal,
    DOG,
    CAT,
    HORSE
);
auto dog = Animal::DOG;
std::cout<<dog;

1
只需将enum类声明更改为enum即可在c ++ 11之前的版本上工作。
Debdatta Basu 2014年

1
您是对的,它起作用了(汽车也只有c ++ 11)。不错的解决方案!如果您还可以为一些枚举设置值,那将是完美的
2014年

我想我看到了类似的东西
谢尔盖(Sergei)

10

我建议混合使用X-宏是最好的解决方案,并使用以下模板功能:

借用marcinkoziukmyopenidcom并扩展

enum Colours {
#   define X(a) a,
#   include "colours.def"
#   undef X
    ColoursCount
};

char const* const colours_str[] = {
#   define X(a) #a,
#   include "colours.def"
#   undef X
    0
};

template <class T> T str2enum( const char* );
template <class T> const char* enum2str( T );

#define STR2ENUM(TYPE,ARRAY) \
template <> \
TYPE str2enum<TYPE>( const char* str ) \
    { \
    for( int i = 0; i < (sizeof(ARRAY)/sizeof(ARRAY[0])); i++ ) \
        if( !strcmp( ARRAY[i], str ) ) \
            return TYPE(i); \
    return TYPE(0); \
    }

#define ENUM2STR(TYPE,ARRAY) \
template <> \
const char* enum2str<TYPE>( TYPE v ) \
    { \
    return ARRAY[v]; \
    }

#define ENUMANDSTR(TYPE,ARRAY)\
    STR2ENUM(TYPE,ARRAY) \
    ENUM2STR(TYPE,ARRAY)

ENUMANDSTR(Colours,colours_str)

colour.def

X(Red)
X(Green)
X(Blue)
X(Cyan)
X(Yellow)
X(Magenta)

有没有办法使枚举字符串数组定义通用?(我不知道如何处理宏中的X宏,而且我也不容易处理模板)
Jonathan

5

我使用以下复制的解决方案:

#define MACROSTR(k) #k

#define X_NUMBERS \
       X(kZero  ) \
       X(kOne   ) \
       X(kTwo   ) \
       X(kThree ) \
       X(kFour  ) \
       X(kMax   )

enum {
#define X(Enum)       Enum,
    X_NUMBERS
#undef X
} kConst;

static char *kConstStr[] = {
#define X(String) MACROSTR(String),
    X_NUMBERS
#undef X
};

int main(void)
{
    int k;
    printf("Hello World!\n\n");

    for (k = 0; k < kMax; k++)
    {
        printf("%s\n", kConstStr[k]);
    }

    return 0;
}

1
这是基本的X宏,我很奇怪,这是这里提出的第一个答案!+1
绕道轻度比赛

4

如果要获取MyEnum 变量的字符串表示形式,则模板不会将其剪切。模板可以专门处理编译时已知的整数值。

但是,如果这是您想要的,请尝试:

#include <iostream>

enum MyEnum { VAL1, VAL2 };

template<MyEnum n> struct StrMyEnum {
    static char const* name() { return "Unknown"; }
};

#define STRENUM(val, str) \
  template<> struct StrMyEnum<val> { \
    static char const* name() { return str; }};

STRENUM(VAL1, "Value 1");
STRENUM(VAL2, "Value 2");

int main() {
  std::cout << StrMyEnum<VAL2>::name();
}

这很冗长,但是会捕获类似您所犯错误的错误-您case VAL1的重复项。


实际上,方法name()并不是必需的。看我的答案。
jfs

3

我想花更多的时间研究这个主题。幸运的是,在野外有很棒的开源解决方案。

即使尚不为人所知,这也是两种不错的方法,

wise_enum

  • 用于C ++ 11/14/17的独立智能枚举库。它支持C ++中的智能枚举类所期望的所有标准功能。
  • 限制:至少需要C ++ 11。

更好的枚举

  • 具有清晰语法的反射式编译时枚举库,位于单个头文件中,没有依赖性。
  • 局限性:基于宏,不能在类内部使用。

2

我很想拥有一张地图m-并将其嵌入到枚举中。

用m [MyEnum.VAL1] =“值1”进行设置;

一切都完成了。



2

您的回答启发了我自己编写一些宏。我的要求如下:

  1. 只将枚举的每个值写入一次,因此没有要维护的重复列表

  2. 不要将枚举值保存在以后包含#include的单独文件中,因此我可以在任何需要的地方编写它

  3. 不要替换枚举本身,我仍然想定义枚举类型,但是除了它之外,我希望能够将每个枚举名称映射到相应的字符串(不影响遗留代码)

  4. 对于那些巨大的枚举,搜索应该快速,因此最好不要切换

此代码创建具有一些值的经典枚举。另外,它创建为std :: map,将每个枚举值映射到其名称(例如map [E_SUNDAY] =“ E_SUNDAY”等)

好的,这是现在的代码:

EnumUtilsImpl.h

map<int, string> & operator , (map<int, string> & dest, 
                               const pair<int, string> & keyValue) {
    dest[keyValue.first] = keyValue.second; 
    return dest;
}

#define ADD_TO_MAP(name, value) pair<int, string>(name, #name)

EnumUtils.h //这是您想在需要执行此操作时要包括的文件,您将使用其中的宏:

#include "EnumUtilsImpl.h"
#define ADD_TO_ENUM(name, value) \
    name value

#define MAKE_ENUM_MAP_GLOBAL(values, mapName) \
    int __makeMap##mapName() {mapName, values(ADD_TO_MAP); return 0;}  \
    int __makeMapTmp##mapName = __makeMap##mapName();

#define MAKE_ENUM_MAP(values, mapName) \
    mapName, values(ADD_TO_MAP);

MyProjectCodeFile.h //这是如何使用它创建自定义枚举的示例:

#include "EnumUtils.h*

#define MyEnumValues(ADD) \
    ADD(val1, ), \
    ADD(val2, ), \
    ADD(val3, = 100), \
    ADD(val4, )

enum MyEnum {
    MyEnumValues(ADD_TO_ENUM)
};

map<int, string> MyEnumStrings;
// this is how you initialize it outside any function
MAKE_ENUM_MAP_GLOBAL(MyEnumValues, MyEnumStrings); 

void MyInitializationMethod()
{ 
    // or you can initialize it inside one of your functions/methods
    MAKE_ENUM_MAP(MyEnumValues, MyEnumStrings); 
}

干杯。


2

这是尝试仅使用一个宏命令在枚举上自动获取<<和>>流运算符...

定义:

#include <string>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <vector>

#define MAKE_STRING(str, ...) #str, MAKE_STRING1_(__VA_ARGS__)
#define MAKE_STRING1_(str, ...) #str, MAKE_STRING2_(__VA_ARGS__)
#define MAKE_STRING2_(str, ...) #str, MAKE_STRING3_(__VA_ARGS__)
#define MAKE_STRING3_(str, ...) #str, MAKE_STRING4_(__VA_ARGS__)
#define MAKE_STRING4_(str, ...) #str, MAKE_STRING5_(__VA_ARGS__)
#define MAKE_STRING5_(str, ...) #str, MAKE_STRING6_(__VA_ARGS__)
#define MAKE_STRING6_(str, ...) #str, MAKE_STRING7_(__VA_ARGS__)
#define MAKE_STRING7_(str, ...) #str, MAKE_STRING8_(__VA_ARGS__)
#define MAKE_STRING8_(str, ...) #str, MAKE_STRING9_(__VA_ARGS__)
#define MAKE_STRING9_(str, ...) #str, MAKE_STRING10_(__VA_ARGS__)
#define MAKE_STRING10_(str) #str

#define MAKE_ENUM(name, ...) MAKE_ENUM_(, name, __VA_ARGS__)
#define MAKE_CLASS_ENUM(name, ...) MAKE_ENUM_(friend, name, __VA_ARGS__)

#define MAKE_ENUM_(attribute, name, ...) name { __VA_ARGS__ }; \
    attribute std::istream& operator>>(std::istream& is, name& e) { \
        const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
        std::string str; \
        std::istream& r = is >> str; \
        const size_t len = sizeof(name##Str)/sizeof(name##Str[0]); \
        const std::vector<std::string> enumStr(name##Str, name##Str + len); \
        const std::vector<std::string>::const_iterator it = std::find(enumStr.begin(), enumStr.end(), str); \
        if (it != enumStr.end())\
            e = name(it - enumStr.begin()); \
        else \
            throw std::runtime_error("Value \"" + str + "\" is not part of enum "#name); \
        return r; \
    }; \
    attribute std::ostream& operator<<(std::ostream& os, const name& e) { \
        const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
        return (os << name##Str[e]); \
    }

用法:

// Declare global enum
enum MAKE_ENUM(Test3, Item13, Item23, Item33, Itdsdgem43);

class Essai {
public:
    // Declare enum inside class
    enum MAKE_CLASS_ENUM(Test, Item1, Item2, Item3, Itdsdgem4);

};

int main() {
    std::cout << Essai::Item1 << std::endl;

    Essai::Test ddd = Essai::Item1;
    std::cout << ddd << std::endl;

    std::istringstream strm("Item2");
    strm >> ddd;

    std::cout << (int) ddd << std::endl;
    std::cout << ddd << std::endl;
}

尽管不确定该方案的局限性,但欢迎评论!


1

在标题中:

enum EFooOptions
 {
FooOptionsA = 0, EFooOptionsMin = 0,
FooOptionsB,
FooOptionsC,
FooOptionsD 
EFooOptionsMax
};
extern const wchar* FOO_OPTIONS[EFooOptionsMax];

在.cpp文件中:

const wchar* FOO_OPTIONS[] = {
    L"One",
    L"Two",
    L"Three",
    L"Four"
};

警告:不要处理错误的数组索引。:)但是,您可以轻松地添加一个函数来从数组中获取字符串之前验证枚举。


确实是一种非常非DRY-SPOT的解决方案。
xtofl

现在您提到DRY。从其他输入文件自动生成的.h和.cpp文件。我希望看到更好的解决方案(不必求助于不必要的复杂性)
moogs

1

我只是想展示使用宏的这种可能的优雅解决方案。这不能解决问题,但我认为这是重新思考问题的好方法。

#define MY_LIST(X) X(value1), X(value2), X(value3)

enum eMyEnum
    {
    MY_LIST(PLAIN)
    };

const char *szMyEnum[] =
    {
    MY_LIST(STRINGY)
    };


int main(int argc, char *argv[])
{

std::cout << szMyEnum[value1] << value1 <<" " <<  szMyEnum[value2] << value2 << std::endl;

return 0;
}

----编辑----

经过一些互联网研究和一些自己的实验,我得出以下解决方案:

//this is the enum definition
#define COLOR_LIST(X) \
  X( RED    ,=21)      \
  X( GREEN  )      \
  X( BLUE   )      \
  X( PURPLE , =242)      \
  X( ORANGE )      \
  X( YELLOW )

//these are the macros
#define enumfunc(enums,value) enums,
#define enumfunc2(enums,value) enums value,
#define ENUM2SWITCHCASE(enums) case(enums): return #enums;

#define AUTOENUM(enumname,listname) enum enumname{listname(enumfunc2)};
#define ENUM2STRTABLE(funname,listname) char* funname(int val) {switch(val) {listname(ENUM2SWITCHCASE) default: return "undef";}}
#define ENUM2STRUCTINFO(spacename,listname) namespace spacename { int values[] = {listname(enumfunc)};int N = sizeof(values)/sizeof(int);ENUM2STRTABLE(enum2str,listname)};

//here the enum and the string enum map table are generated
AUTOENUM(testenum,COLOR_LIST)
ENUM2STRTABLE(testfunenum,COLOR_LIST)
ENUM2STRUCTINFO(colorinfo,COLOR_LIST)//colorinfo structur {int values[]; int N; char * enum2str(int);}

//debug macros
#define str(a) #a
#define xstr(a) str(a)


int main( int argc, char** argv )
{
testenum x = YELLOW;
std::cout << testfunenum(GREEN) << "   " << testfunenum(PURPLE) << PURPLE << "  " << testfunenum(x);

for (int i=0;i< colorinfo::N;i++)
std::cout << std::endl << colorinfo::values[i] <<  "  "<< colorinfo::enum2str(colorinfo::values[i]);

  return EXIT_SUCCESS;
}

我只是想发布它,也许有人可以找到这个解决方案有用。不需要模板类,不需要c ++ 11,也不需要boost,因此也可以用于简单的C语言。

----编辑2 ----

使用两个以上的枚举时,信息表可能会产生一些问题(编译器问题)。以下变通办法起作用:

#define ENUM2STRUCTINFO(spacename,listname) namespace spacename { int spacename##_##values[] = {listname(enumfunc)};int spacename##_##N = sizeof(spacename##_##values)/sizeof(int);ENUM2STRTABLE(spacename##_##enum2str,listname)};

1
typedef enum {
    ERR_CODE_OK = 0,
    ERR_CODE_SNAP,

    ERR_CODE_NUM
} ERR_CODE;

const char* g_err_msg[ERR_CODE_NUM] = {
    /* ERR_CODE_OK   */ "OK",
    /* ERR_CODE_SNAP */ "Oh, snap!",
};

以上是我的简单解决方案。它的一个好处是控制消息数组大小的'NUM',它还防止了超出边界的访问(如果您明智地使用它)。

您还可以定义一个函数来获取字符串:

const char* get_err_msg(ERR_CODE code) {
    return g_err_msg[code];
}

除了我的解决方案,我还发现以下有趣的事情。它通常解决了上述问题的同步问题。

幻灯片在这里:http//www.slideshare.net/arunksaha/touchless-enum-tostring-28684724

代码在这里:https : //github.com/arunksaha/enum_to_string


1

我知道我要参加聚会很晚,但是对于所有其他访问此页面的人,您都可以尝试一下,它比那里的一切都容易,并且更有意义:

namespace texs {
    typedef std::string Type;
    Type apple = "apple";
    Type wood = "wood";
}

您是否建议使用字符串而不完全使用枚举?那并不能真正解决问题。
罗迪

0

最近,我在供应商库(Fincad)中遇到了同样的问题。幸运的是,供应商为所有枚举提供了xml双重注释。我最终为每种枚举类型生成了一个映射,并为每种枚举提供了查找功能。该技术还允许您拦截枚举范围之外的查找。

我确信swig可以为您做类似的事情,但是我很乐意提供用ruby编写的代码生成工具。

这是代码示例:

std::map<std::string, switches::FCSW2::type> init_FCSW2_map() {
        std::map<std::string, switches::FCSW2::type> ans;
        ans["Act365Fixed"] = FCSW2::Act365Fixed;
        ans["actual/365 (fixed)"] = FCSW2::Act365Fixed;
        ans["Act360"] = FCSW2::Act360;
        ans["actual/360"] = FCSW2::Act360;
        ans["Act365Act"] = FCSW2::Act365Act;
        ans["actual/365 (actual)"] = FCSW2::Act365Act;
        ans["ISDA30360"] = FCSW2::ISDA30360;
        ans["30/360 (ISDA)"] = FCSW2::ISDA30360;
        ans["ISMA30E360"] = FCSW2::ISMA30E360;
        ans["30E/360 (30/360 ISMA)"] = FCSW2::ISMA30E360;
        return ans;
}
switches::FCSW2::type FCSW2_lookup(const char* fincad_switch) {
        static std::map<std::string, switches::FCSW2::type> switch_map = init_FCSW2_map();
        std::map<std::string, switches::FCSW2::type>::iterator it = switch_map.find(fincad_switch);
        if(it != switch_map.end()) {
                return it->second;
        } else {
                throw FCSwitchLookupError("Bad Match: FCSW2");
        }
}

似乎您想采用另一种方式(将枚举转换为字符串,而不是将字符串枚举为枚举),但这对于反转来说应该是微不足道的。

W


1
a)是否有人发现这绝对不可读?一些typedef和使用声明将大大提高可读性。b)局部静态声明不是线程安全的。c)使用const string&代替char *,d)包含在抛出的异常中找不到的值怎么办?
Alastair

0

查看以下语法是否适合您:

// WeekEnd enumeration
enum WeekEnd
{
    Sunday = 1,
    Saturday = 7
};

// String support for WeekEnd
Begin_Enum_String( WeekEnd )
{
    Enum_String( Sunday );
    Enum_String( Saturday );
}
End_Enum_String;

// Convert from WeekEnd to string
const std::string &str = EnumString<WeekEnd>::From( Saturday );
// str should now be "Saturday"

// Convert from string to WeekEnd
WeekEnd w;
EnumString<WeekEnd>::To( w, "Sunday" );
// w should now be Sunday

如果是这样,那么您可能想看看这篇文章:http :
//www.gamedev.net/reference/snippets/features/cppstringizing/


0

这是我根据SO的一点点努力做出的努力。for_each将必须扩展为支持20多个枚举值。在Visual Studio 2019,clang和gcc上进行了测试。C ++ 11

#define _enum_expand(arg) arg
#define _enum_select_for_each(_,_0, _1, _2,_3,_4, _5, _6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,N, ...) N
#define _enum_for_each_0(_call, arg0,arg1,...)
#define _enum_for_each_1(_call, arg0,arg1) _call(arg0,arg1)
#define _enum_for_each_2(_call, arg0,arg1, ...) _call(arg0,arg1)  _enum_expand(_enum_for_each_1(_call,arg0, __VA_ARGS__))
#define _enum_for_each_3(_call, arg0,arg1, ...) _call(arg0,arg1)  _enum_expand(_enum_for_each_2(_call,arg0, __VA_ARGS__))
#define _enum_for_each_4(_call, arg0,arg1, ...) _call(arg0,arg1)  _enum_expand(_enum_for_each_3(_call,arg0, __VA_ARGS__))
#define _enum_for_each_5(_call, arg0,arg1, ...) _call(arg0,arg1)  _enum_expand(_enum_for_each_4(_call,arg0, __VA_ARGS__))
#define _enum_for_each_6(_call, arg0,arg1, ...) _call(arg0,arg1)  _enum_expand(_enum_for_each_5(_call,arg0, __VA_ARGS__))
#define _enum_for_each_7(_call, arg0,arg1, ...) _call(arg0,arg1)  _enum_expand(_enum_for_each_6(_call,arg0, __VA_ARGS__))
#define _enum_for_each_8(_call, arg0,arg1, ...) _call(arg0,arg1)  _enum_expand(_enum_for_each_7(_call,arg0, __VA_ARGS__))
#define _enum_for_each_9(_call, arg0,arg1, ...) _call(arg0,arg1)  _enum_expand(_enum_for_each_8(_call,arg0, __VA_ARGS__))
#define _enum_for_each_10(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_9(_call,arg0, __VA_ARGS__))
#define _enum_for_each_11(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_10(_call,arg0, __VA_ARGS__))
#define _enum_for_each_12(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_11(_call,arg0, __VA_ARGS__))
#define _enum_for_each_13(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_12(_call,arg0, __VA_ARGS__))
#define _enum_for_each_14(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_13(_call,arg0, __VA_ARGS__))
#define _enum_for_each_15(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_14(_call,arg0, __VA_ARGS__))
#define _enum_for_each_16(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_15(_call,arg0, __VA_ARGS__))
#define _enum_for_each_17(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_16(_call,arg0, __VA_ARGS__))
#define _enum_for_each_18(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_17(_call,arg0, __VA_ARGS__))
#define _enum_for_each_19(_call, arg0,arg1, ...) _call(arg) _enum_expand(_enum_for_each_18(_call,arg0, __VA_ARGS__))
#define _enum_for_each(arg, ...) \
    _enum_expand(_enum_select_for_each(_, ##__VA_ARGS__, \
    _enum_for_each_19, _enum_for_each_18, _enum_for_each_17, _enum_for_each_16, _enum_for_each_15, \
    _enum_for_each_14, _enum_for_each_13, _enum_for_each_12, _enum_for_each_11, _enum_for_each_10, \
    _enum_for_each_9,  _enum_for_each_8,  _enum_for_each_7,  _enum_for_each_6,  _enum_for_each_5,  \
    _enum_for_each_4,  _enum_for_each_3,  _enum_for_each_2,  _enum_for_each_1,  _enum_for_each_0)(arg, ##__VA_ARGS__))

#define _enum_strip_args_1(arg0) arg0
#define _enum_strip_args_2(arg0, arg1) arg0, arg1
#define _enum_make_args(...) (__VA_ARGS__)

#define _enum_elem_arity1_1(arg) arg,
#define _enum_elem_arity1( ...) _enum_expand(_enum_elem_arity1_1 __VA_ARGS__)
#define _enum_elem_arity2_1(arg0,arg1) arg0 = arg1,
#define _enum_elem_arity2( ...) _enum_expand(_enum_elem_arity2_1 __VA_ARGS__)

#define _enum_elem_select_arity_2(_0, _1, NAME,...) NAME
#define _enum_elem_select_arity_1(...) _enum_expand(_enum_elem_select_arity_2(__VA_ARGS__, _enum_elem_arity2,_enum_elem_arity1,_))
#define _enum_elem_select_arity(enum_type,...) _enum_expand(_enum_elem_select_arity_1 __VA_ARGS__)(__VA_ARGS__)

#define _enum_str_arity1_1(enum_type,arg) { enum_type::arg,#arg },
#define _enum_str_arity1(enum_type,...) _enum_expand(_enum_str_arity1_1 _enum_make_args( enum_type, _enum_expand(_enum_strip_args_1 __VA_ARGS__)))
#define _enum_str_arity2_1(enum_type,arg,value) { enum_type::arg,#arg },
#define _enum_str_arity2(enum_type, ...) _enum_expand(_enum_str_arity2_1 _enum_make_args( enum_type, _enum_expand(_enum_strip_args_2 __VA_ARGS__)))
#define _enum_str_select_arity_2(_0, _1, NAME,...) NAME
#define _enum_str_select_arity_1(...) _enum_expand(_enum_str_select_arity_2(__VA_ARGS__, _enum_str_arity2,_enum_str_arity1,_))
#define _enum_str_select_arity(enum_type,...) _enum_expand(_enum_str_select_arity_1 __VA_ARGS__)(enum_type,__VA_ARGS__)

#define error_code_enum(enum_type,...)  enum class enum_type {              \
    _enum_expand(_enum_for_each(_enum_elem_select_arity,enum_type, ##__VA_ARGS__))};  \
    namespace _ ## enum_type ## _detail { \
        template <typename> struct _ ## enum_type ## _error_code{ \
            static const std::map<enum_type, const char*> enum_type ## _map; \
        }; \
            template <typename T> \
            const std::map<enum_type, const char*> _ ## enum_type ## _error_code<T>::enum_type ## _map = { \
                _enum_expand(_enum_for_each(_enum_str_select_arity,enum_type,  ##__VA_ARGS__)) \
        }; \
    } \
    inline const char* get_error_code_name(const enum_type& value) { \
        return _ ## enum_type ## _detail::_ ## enum_type ## _error_code<enum_type>::enum_type ## _map.find(value)->second; \
    } 

error_code_enum(myenum,
    (one, 1),
    (two)
);

产生以下代码

enum class myenum { 
    one = 1,
    two,
};
namespace _myenum_detail {
    template <typename>
    struct _myenum_error_code {
        static const std::map<myenum, const char*> myenum_map;
    };
    template <typename T>
    const std::map<myenum, const char*> _myenum_error_code<T>::myenum_map = {
        { myenum::one, "one" }, 
        { myenum::two, "two" },
    };
}
inline const char* get_error_code_name(const myenum& value) { 
    return _myenum_detail::_myenum_error_code<myenum>::myenum_map.find(value)->second; 
}

要使用世界上最常用的编程语言之一来使用预处理器,您必须克服的麻烦实在令人遗憾。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.