2016-09-25 19 views
1

如果key類型T不是有效密鑰,我想拋出類型domain_error的異常。 但我不知道如何將任何類型的T轉換爲字符串,只要定義了T::operator std::string(),例如int不支持此操作。Excpetion消息:插入字符串表示錯誤值

這是obvioulsy錯誤的,因爲它僅適用於非常特殊的類型:

throw std::domain_error("key error: "+static_cast<std::string>(key)); 

如何才能做到這一點?

編輯

的建議後,我的解決方案中使用的模板specilisation

template <class T> std::string to_string(const T t) 
    { 
     return static_cast<std::string>(t); 
    } 

    template <> std::string to_string<unsigned int>(const unsigned int i) 
    { 
     std::stringstream ss; 
     std::string ret; 
     ss << i; 
     ss >> ret; 
     return ret; 
    } 

...

std::string domain_error(const IS& is) const 
    { 
     using namespace IDTranslator_detail; 
     return "key error: "+to_string(is), "error"; 
    } 

...

throw std::domain_error(domain_error(key)); 

回答

1

它不能如上所述,在所有情況下100%。

您必須指定模板的一部分契約是,無論將哪個類作爲參數傳遞,它必須支持operator std::string

作爲合同的一部分,您也可以編寫數字類型,您也可以在模板中實現這一點,作爲使用std::to_string的專業化。

對於一個健壯的實現,在這種情況下我會用SFINAE嘗試std::to_stringoperator std::string,如果發生故障,則使用一些溫和的標籤,如異常消息「未知類型」。或許,使用typeid和我的編譯器的demangler一起,至少可以從中得到一個C++類型的名稱。

+0

謝謝,我做了模板專業化。 –

相關問題