我想要一种在一个且仅一个位置声明错误代码(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 测试以检查地图的一致性)。如果您没有数千个错误代码,那应该不是问题(并且可能有解决方法......)