在C++中将错误代码映射到字符串

Ged*_*nas 4 c++ string error-code

将错误代码从枚举映射到字符串的更有效方法是什么?(在C++中)

例如,现在我正在做这样的事情:

std::string ErrorCodeToString(enum errorCode)
{
   switch (errorCode)
   {
      case ERROR_ONE:   return "ERROR_ONE";
      case ERROR_TWO:   return "ERROR_TWO";
      ...
      default:
         break;
   }

   return "UNKNOWN";
}
Run Code Online (Sandbox Code Playgroud)

如果我做这样的事情会以任何方式提高效率吗?:

#define ToStr( name ) # name;

std::string MapError(enum errorCode)
{
   switch (errorCode)
   {
      case ERROR_ONE:   return ToStr(ERROR_ONE);
      case ERROR_TWO:   return ToStr(ERROR_TWO);
      ...
      default:
         break;
   }

   return "UNKNOWN";
}
Run Code Online (Sandbox Code Playgroud)

也许有人对此有任何建议或想法?谢谢.

Man*_*rse 6

如果您打算使用宏,为什么不一直使用:

std::string MapError(enum errorCode)
{
    #define MAP_ERROR_CODE(code) case code: return #code ;
    switch (errorCode)
    {
       MAP_ERROR_CODE(ERROR_ONE)
       MAP_ERROR_CODE(ERROR_TWO)
       ...
    }
    #undef MAP_ERROR_CODE
    return "UNKNOWN";
}
Run Code Online (Sandbox Code Playgroud)


jpo*_*o38 5

我希望有一种方法可以在一个且只有一个地方声明错误代码(int)和字符串描述(任何字符串),上面的例子都不允许这样做.

所以我声明了一个存储int和string的简单类,并为int-> string转换维护一个静态映射.我还添加了一个"自动转换为"int函数:

class Error
{
public:
    Error( int _value, const std::string& _str )
    {
        value = _value;
        message = _str;
#ifdef _DEBUG
        ErrorMap::iterator found = GetErrorMap().find( value );
        if ( found != GetErrorMap().end() )
            assert( found->second == message );
#endif
        GetErrorMap()[value] = message;
    }

    // auto-cast Error to integer error code
    operator int() { return value; }

private:
    int value;
    std::string message;

    typedef std::map<int,std::string> ErrorMap;
    static ErrorMap& GetErrorMap()
    {
        static ErrorMap errMap;
        return errMap;
    }

public:

    static std::string GetErrorString( int value )
    {
        ErrorMap::iterator found = GetErrorMap().find( value );
        if ( found == GetErrorMap().end() )
        {
            assert( false );
            return "";
        }
        else
        {
            return found->second;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

然后,您只需声明错误代码如下:

static Error ERROR_SUCCESS(                 0, "The operation succeeded" );
static Error ERROR_SYSTEM_NOT_INITIALIZED(  1, "System is not initialised yet" );
static Error ERROR_INTERNAL(                2, "Internal error" );
static Error ERROR_NOT_IMPLEMENTED(         3, "Function not implemented yet" );
Run Code Online (Sandbox Code Playgroud)

然后,返回int的任何函数都可以返回1

return ERROR_SYSTEM_NOT_INITIALIZED;
Run Code Online (Sandbox Code Playgroud)

并且,您的库的客户端程序在调用时将获得"系统尚未初始化"

Error::GetErrorString( 1 );
Run Code Online (Sandbox Code Playgroud)

要么:

Error::GetErrorString( ERROR_SYSTEM_NOT_INITIALIZED );
Run Code Online (Sandbox Code Playgroud)

我看到的唯一限制是静态错误对象被创建多次,如果.h文件声明它们被许多.cpp包含(这就是为什么我在构造函数中进行_DEBUG测试以检查映射的一致性).如果您没有数以千计的错误代码,那应该不是问题(并且可能有解决方法......)