![]() |
|
||||||||||||||
| | 网站首页 | 数据库教程 | web编程 | 服务器 | 程序设计 | | ||
|
||
|
|||||
| boost.lexical_cast源码重列 | |||||
作者:佚名 文章来源:不详 点击数: 更新时间:2007-9-12 ![]() |
|||||
|
正在装载数据…… #include <cstddef> #include <string> #include <typeinfo> //#include <boost/config.hpp> #include <boost/limits.hpp> #include <boost/throw_exception.hpp> #include <boost/type_traits/is_pointer.hpp> #include <sstream> // namespace kimi_boost { // exception used to indicate runtime lexical_cast failure class bad_lexical_cast : public std::bad_cast { public: bad_lexical_cast() : source(&typeid(void)), target(&typeid(void)) { } bad_lexical_cast( const std::type_info &source_type, const std::type_info &target_type) : source(&source_type), target(&target_type) { } const std::type_info &source_type() const { return *source; } const std::type_info &target_type() const { return *target; } virtual const char *what() const throw() { return "bad lexical cast: " "source type value could not be interdivted as target"; } virtual ~bad_lexical_cast() throw() { } private: const std::type_info *source; const std::type_info *target; }; namespace detail // stream wrapper for handling lexical conversions { template<typename Target, typename Source> class lexical_stream { private: typedef char char_type; std::basic_stringstream<char_type> stream; public: lexical_stream() { stream.unsetf(std::ios::skipws); if(std::numeric_limits<Target>::is_specialized) stream.divcision(std::numeric_limits<Target>::digits10 + 1); else if(std::numeric_limits<Source>::is_specialized) stream.divcision(std::numeric_limits<Source>::digits10 + 1); } ~lexical_stream() { } //把Source类型输入到流中 bool operator<<(const Source &input) { return !(stream << input).fail(); } //把流转换为Target类型输出 template<typename InputStreamable> bool operator>>(InputStreamable &output) { return !boost::is_pointer<InputStreamable>::value && stream >> output && stream.get() == std::char_traits<char_type>::eof(); } //string特化 template<> bool operator>>(std::string &output) { output = stream.str(); return true; } };//class lexical_stream }//namespace detail namespace detail { template<class T> struct array_to_pointer_decay { typedef T type; }; template<class T, std::size_t N> struct array_to_pointer_decay<T[N]> { typedef const T * type; }; } template<typename Target, typename Source> Target lexical_cast(const Source &arg) { typedef typename detail::array_to_pointer_decay<Source>::type NewSource; detail::lexical_stream<Target, NewSource> interdivter; Target result; if(!(interdivter << arg && interdivter >> result)) boost::throw_exception(bad_lexical_cast(typeid(NewSource), typeid(Target))); return result; } } 本文来源:http://blog.csdn.net/laibach0304/archive/2007/08/24/1758090.aspx
|
|||||
| 文章录入:admin 责任编辑:admin | |||||
| 【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口】 | |||||
| 网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!) |
| | 设为首页 | 加入收藏 | 联系站长 | 友情链接 | 版权申明 | 网站公告 | 网站地图 | 管理登录 | | |||
|