T
のkey
が有効なキーでない場合、タイプdomain_error
の例外をスローしたいとします。 しかし、T::operator std::string()
が定義されている限り、どのようにタイプT
を文字列に変換できるかわかりません。たとえば、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));
ありがとう、私はテンプレートの専門をしました。 –