4

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

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

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

   return "UNKNOWN";
}

如果我做这样的事情会更有效吗?:

#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";
}

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

4

6 回答 6

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";
}
于 2013-01-11T13:47:30.850 回答
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;
        }
    }
};

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

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" );

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

return ERROR_SYSTEM_NOT_INITIALIZED;

并且,您的库的客户端程序在调用时会得到“系统尚未初始化”

Error::GetErrorString( 1 );

或者:

Error::GetErrorString( ERROR_SYSTEM_NOT_INITIALIZED );

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

于 2014-02-24T15:09:02.737 回答
4
enum errors {
    error_zero,
    error_one,
    error_two
};

namespace {
const char *error_names[] = {
    "Error one",
    "Error two",
    "Error three"
};
}

std::string map_error(errors err) {
    return error_names[err];
}
于 2013-01-11T13:49:05.100 回答
4

您建议的替代方案不再有效,但您可以通过两种方式改进:

  1. 您显然在errorCode枚举和此函数之间存在重复。
  2. 由于枚举值与字符串给出的名称相同,因此您的函数中也存在某种重复。

你可以用一点预处理魔法来修复这两个问题:

// This is your definition of available error codes
#define ERROR_CODES \
  ERROR_CODE(ERROR_ONE) \
  ERROR_CODE(ERROR_TWO) \
  ERROR_CODE(ERROR_THREE)

// Define ERROR_CODE macro appropriately to get a nice enum definition
#define ERROR_CODE(a) ,a
enum ErrorCode {
  None,
  ERROR_CODES
};
#undef ERROR_CODE

// Define ERROR_CODE macro differently here to get the enum -> string mapping
std::string MapError(enum errorCode)
{
   #define ERROR_CODE(a) case a: return #a;

   switch (errorCode)
   {
      case None: return "None";
      ERROR_CODES
   }
}
于 2013-01-11T13:50:02.043 回答
2

不,在预处理器传递您的代码后,两者将完全相同。唯一的问题是第二种方法不太容易出现拼写错误。

我想说您实施的已经是一个很好的解决方案。

于 2013-01-11T13:47:15.023 回答
1

我知道这是一个旧线程,但我确实喜欢 Frerich Raabe 的方法,并让它在 VS 中正常工作:

#define ERROR_CODES \
    ERROR_CODE(NO_ERROR) \
    ERROR_CODE(ERROR_ONE) \
    ERROR_CODE(ERROR_TWO) \
    ERROR_CODE(ERROR_THREE) \
    ERROR_CODE(ERROR_FOUR)

#define ERROR_CODE(code) code,
typedef enum { ERROR_CODES } ErrorCodes;
#undef ERROR_CODE

const char *MapError(const int errorCode)
{
#define ERROR_CODE(code) case code: return #code;   
    switch (errorCode)
    {
        ERROR_CODES
    default: return "UNKNOWN ERROR";
    };
#undef ERROR_CODE
}
于 2017-01-03T01:50:23.963 回答