C++ 模拟boost-u-cast操作
不幸的是,在我当前的项目中,我不能使用boost,所以我试图模仿C++ 模拟boost-u-cast操作,c++,boost,C++,Boost,不幸的是,在我当前的项目中,我不能使用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 st
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;
}
//将字符串转换为原语,有效
//(不知羞耻地从另一个堆栈溢出柱上取下)
样板
T string_实用程序::词法转换(const string&in)
{
串流输出(in);
T结果;
if((out>>result).fail()| |!(out>>std::ws).eof())
{
抛出std::bad_cast();
}
返回结果;
}
//将基元转换为字符串
//行得通,不是我想要的语法
样板
字符串实用工具::词法转换(const T in)
{
流出来;
输出>结果)。失败()
{
抛出std::bad_cast();
}
返回结果;
}
我希望能够使用相同的语法来保持一致性,但我想不出来
将字符串转换为基元很好
inti=lexical_cast(“123”)代码>
然而,另一种方式是:
string foo = lexical_cast(123);
// What I want
// string foo = lexical_cast<string>(123);
stringfoo=lexical_cast(123);
//我想要什么
//字符串foo=词法转换(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;
}
template Out词法转换(输入中)
{
细流ss;
ss>r.fail()| |!(ss>>std::ws.eof())
{
抛出std::bad_cast();
}
返回r;
}
词法转换的基本模板代码是:
template<typename In, typename Out> Out lexical_cast(In in) {
stringstream ss;
ss << in;
if (ss.fail()) throw bad_cast();
ss >> out;
return out;
}
template Out词法转换(In-In){
细流ss;
ss>out;
返回;
}
根据需要为(In==string)等添加错误检查和专门化。词法转换的基本模板代码是:
template<typename In, typename Out> Out lexical_cast(In in) {
stringstream ss;
ss << in;
if (ss.fail()) throw bad_cast();
ss >> out;
return out;
}
template Out词法转换(In-In){
细流ss;
ss>out;
返回;
}
根据需要为(In==string)等添加错误检查和专门化。为什么不直接从boost库中剪切和粘贴代码?为什么不直接从boost库中剪切和粘贴代码?