函数声明:
template <typename Target, typename Source>
inline Target lexical_cast(const Source &;
lexical_cast将入参转换成和返回值相同类型,如果发生异常,则抛出boost::bad_lexical_cast的异常:
string s("1895x");
try
{
int i = boost::lexical_cast<int>(s);
cout<<i<<endl;
}
catch (boost::bad_lexical_cast& bad)
{
cout<<bad.what()<<endl;
}
关于lexical_cast的实现:
本质使用了ostream,这里也可以自己实现一个,比如:
namespace sr
{
template<typename DestType,typename SrcType>
DestType lexical_cast(SrcType src)
{
stringstream os;
os<<src;
DestType dest;
os>>dest;
return dest;
}
}