枚举到字符串:如果无效/未找到,则返回枚举整数值 [英] Enum to string : return the enum integer value if invalid / not found
问题描述
所以,我为几个使用了很多枚举的枚举实现了一个 enumToString
函数(经常在SO中提出:有没有一种将C ++枚举转换为字符串的简单方法?,将枚举类型的变量用作C中的字符串的简单方法?,...)。
这使得错误消息更容易调试,但是我必须保留这个功能,以便有时添加没有字符串描述的值。
So, I implemented an enumToString
function for several enums that I use a lot (often asked in SO: Is there a simple way to convert C++ enum to string?, Easy way to use variables of enum types as string in C?, ...).
This makes the error messages WAY easier to debug, but I have to maintain the function to add the values that have no string description sometimes.
我的代码看起来像这样:
My code looks like this:
typedef std::map<my_enum_e, const char *> enum_map_t;
static bool s_enum_map_initialized = false;
static enum_map_t s_enum_strings;
static void s_init_maps()
{
#define ADD_ENUM( X ) s_enum_strings[X] = #X;
if( s_enum_strings.size() == 0)
{
ADD_CLASS( MY_ENUM_1 );
ADD_CLASS( MY_ENUM_2 );
/* ... all enums */
}
s_enum_map_initialized = true;
}
const char *Tools::enumCString( my_enum_e e )
{
if( ! s_enum_map_initialized )
{
s_init_maps();
}
// todo: use the iterator instead of searching twice
if( s_enum_strings.find(e) != s_enum_strings.end() )
{
return s_class_strings[e];
}
return "(unknown enum_e)";
}
现在,我想要的是,当我不要在地图中找到枚举,以返回(未知的枚举%d),e
。这将给我我想念的枚举的价值。
Now, what I want, is that when I don't find the enum in the map, to return "(unknown enum %d)", e
. Which will give me the value of the enum I missed.
这样,即使我没有添加到地图,我仍然有它的价值,我可以调试我的程序。
This way, even if I didn't add it to the map, I still have its value and I can debug my program.
我找不到一种简单的方式:堆栈上串联的stringstream将在返回后立即销毁,一个静态 stringstream不是线程安全的,...
I can't find a way to do that simply: a stringstream instanciated on the stack will be destroyed right after the return, a static stringstream is not thread-safe, ...
编辑:当然,使用 std :: string
作为返回类型将允许我格式化,但是我在代码中经常调用这些函数,我想传递一个 const char *
指针更快,因为我不需要每次将std :: string推入堆栈。
edit: of course, using a std::string
as return type would allow me to format it, but I call these functions very often in my code, I figured passing a const char *
pointer is faster, since I don't have to push the std::string onto the stack each time.
任何解决方案?
推荐答案
返回一个 std :: string
而不是一个 char *
。
这将允许您使用 std :: stringstream
来生成您的消息。那么调用站点就只需要在 std :: string
上使用 .c_str()
成员函数来获取C风格的指针(如果需要)。
This would allow you to use a std::stringstream
to generate your message. The calling site would then just have to use the .c_str( )
member function on std::string
to get the C-style pointer (if required).
这篇关于枚举到字符串:如果无效/未找到,则返回枚举整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!