[boost]lexical_cast简介

来源:互联网 发布:ubuntu qq2015下载 编辑:程序博客网 时间:2024/06/10 13:54

函数声明:

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;}}


原创粉丝点击