枚举到字符串:如果无效/未找到,则返回枚举整数值 [英] Enum to string : return the enum integer value if invalid / not found
问题描述
所以,我实现了一个 enumToString
函数为我使用了很多枚举(通常在SO:,轻松地使用枚举类型的变量作为C中的字符串?,...)。
这使错误消息更容易调试,但我必须保持该函数添加没有字符串描述有时的值。
So, I implemented an enumToString
function for several enums that I use a lot (often asked in SO: Is there a simple script 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.
我的代码看像这样:
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 instanciated在堆栈将被销毁后立即返回,一个 static 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 *
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屋!