`
阿尔萨斯
  • 浏览: 4185715 次
社区版块
存档分类
最新评论

关于lexical_cast,一点补充

 
阅读更多
<iframe align="center" marginwidth="0" marginheight="0" src="http://www.zealware.com/csdnblog.html" frameborder="0" width="728" scrolling="no" height="90"></iframe>

看了凌杰的文章(http://blog.csdn.net/owl2008/archive/2004/09/28/119595.aspx),也想补充两句。lexical_cast比起stringstream来说,的确不一定简洁,当然,其语义和可读性都有提高,但同时也失之灵活。例如下面的情况,似乎就无法用lexical_cast办到。

#include <sstream><br>using namespace std;</sstream>

int main(int, char*[]) {

string hex_str = "0x10";
int i;

std::stringstream convert(hex_str);

convert >> hex >> i;

return 0;
}

如果想像笔者这样在16进制的整数和字符串之间转换,似乎还不得不用stringstream,我阅读了lexical_cast的代码,其实它就是用stringstream实现的,lexical_cast函数本身的代码非常短,如下:

template<typename target typename source><br>Target lexical_cast(Source arg)<br>{<br>detail::lexical_stream<target source> interpreter;<br>Target result;</target></typename>

if(!(interpreter > result))
throw_exception(bad_lexical_cast(typeid(Target), typeid(Source)));
return result;
}

主要的实现部分在lexical_stream的两个重载方法:> 中,

..........
bool operator{
return !(stream }

template<typename inputstreamable><br>bool operator&gt;&gt;(InputStreamable &amp;output)<br>{<br>return !is_pointer<inputstreamable>::value &amp;&amp;<br>stream &gt;&gt; output &amp;&amp;<br>(stream &gt;&gt; std::ws).eof();<br>}<br><br>bool operator&gt;&gt;(std::string &amp;output)<br>{<br>#if defined(BOOST_NO_STRINGSTREAM)<br>stream #endif<br>output = stream.str();<br>return true;<br>}</inputstreamable></typename>
..........

当然,其中的stream是一个经过处理的stringstream,让它可以适应不同的编译器。从这个实现可以看到,我们似乎没有地方可以插入自己的 >> hex >> 之类的代码。也许可以通过对传入的output类型做一个wrapper来实现,但是如果有这个功夫,那又何苦,还不如直接用stringstream更快捷。




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics