残念ながら、現在のプロジェクトではブーストを使用できないため、ブーストの動作を模倣しようとしていますboost::lexical_cast
(ブーストのほとんどのエラー チェックを除く)。私は次の機能を持っています。
// Convert a string to a primitive, works
// (Shamelessly taken from another stack overflow post)
template <typename T>
T string_utility::lexical_cast(const string &in)
{
stringstream out(in);
T result;
if ((out >> result).fail() || !(out >> std::ws).eof())
{
throw std::bad_cast();
}
return result;
}
// Convert a primitive to a string
// Works, not quite the syntax I want
template <typename T>
string string_utility::lexical_cast(const T in)
{
stringstream out;
out << in;
string result;
if ((out >> result).fail())
{
throw std::bad_cast();
}
return result;
}
一貫性のために両方に同じ構文を使用できることを望んでいましたが、わかりません。
文字列をプリミティブに変換することは問題ありません。
int i = lexical_cast<int>("123");
ただし、逆の場合は次のようになります。
string foo = lexical_cast(123);
// What I want
// string foo = lexical_cast<string>(123);
編集:ecatmur に感謝します。テンプレートのパラメーターを切り替える必要がありましたが、次のようにすると、まさに私が望んでいることを実行できます。
template<typename Out, typename In> Out lexical_cast(In input)
{
stringstream ss;
ss << input;
Out r;
if ((ss >> r).fail() || !(ss >> std::ws).eof())
{
throw std::bad_cast();
}
return r;
}