不幸的是,在我当前的项目中,我不能使用boost,所以我试图模仿boost::lexical_cast的行为(减去boost的大部分错误检查)。我有以下功能,它们可以工作。
// 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;
}发布于 2012-07-12 15:26:07
lexical_cast的基本模板代码是:
template<typename In, typename Out> Out lexical_cast(In in) {
stringstream ss;
ss << in;
if (ss.fail()) throw bad_cast();
ss >> out;
return out;
}根据需要为( ==字符串)等添加错误检查和专门化。
https://stackoverflow.com/questions/11455161
复制相似问题