我就想辦法有錯誤代碼(int)和字符串描述(任何字符串)在一個聲明,只有一個單一的地方上面的例子都沒有允許。
所以我宣佈了一個簡單的類,存儲int和string,併爲int-> string轉換維護一個靜態映射。我還添加了一個「自動投地」整數功能:
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(ERROR_SYSTEM_NOT_INITIALIZED);
我看到的唯一限制是靜態的錯誤對象被創建多次,如果.h文件中聲明它們是由許多的.cpp包括(這就是爲什麼我做了_DEBUG測試在構造函數檢查地圖的一致性)。如果你沒有成千上萬的錯誤代碼,它不應該是一個問題(並且可能有一個解決方法...)
如果你正在考慮運行時的性能,這兩個是完全一樣的。 – Angew
[如何將枚舉類型變量轉換爲字符串?](http://stackoverflow.com/questions/5093460/how-to-convert-an-enum-type-variable-to-a-string) –
我會忽略'default:'分支;如果你這樣做了,那麼如果你忘記包含所有的代碼,你應該得到一個編譯器警告。 –