直接上例子,优雅实现
const char * p = get_msg_str(E_THIRD);
简单实现
#define CODE_MSG(XX) \
XX(E_FIRST, "the first") \
XX(E_SECOND, "the second") \
XX(E_THIRD, "the third") \
#define E_CODE_T(name, _) name,
enum e_type
{
E_E,
CODE_MSG(E_CODE_T)
};
#define GET_MSG(name, msg) case name: return msg;
const char* get_msg_str(e_type type)
{
switch (type)
{
CODE_MSG(GET_MSG)
}
return "";
}
也可以稍微冗余
enum e_type
{
E_E,
E_FIRST,
E_SECOND,
E_THIRD,
};
#define CODE_MSG(XX) \
XX(E_FIRST, "the first") \
XX(E_SECOND, "the second") \
XX(E_THIRD, "the third") \
#define GET_MSG(name, msg) case name: return msg;
const char* get_msg_str(e_type type)
{
switch (type)
{
CODE_MSG(GET_MSG)
}
return "";
}
灵活的实现,参考 libuv实现
#define e__first 1
#define e__second 2
#define e__third 3
#define code_msg(xx) \
xx(first, "the first") \
xx(second, "the second") \
xx(third, "the third") \
enum e_type
{
#define xx(code, _) e_## code = e__ ## code,
code_msg(xx)
#undef xx
};
#define get_msg(name, msg) case e_ ## name: return msg;
const char* get_msg_str(e_type type)
{
switch (type)
{
code_msg(get_msg)
}
return "";
}
//get errcode left hand str
#define get_msg_ex(name, _) case e_ ## name: return #name;
const char* get_msg_str_ex(e_type type)
{
switch (type)
{
code_msg(get_msg_ex)
}
return "";
}