基于stringstream的类型转换封装

用法:

lexical::cast_to<TypeTo>::from<TypeFrom>(FromValue);

double a = lexical::cast_to<double>::from("3.1416");

特点:

接口一目了然。能进行基本类型间的转换。


实现:

使用stringstream

有一个问题就是如果源类型和目标类型都是string,即stringstream << in和 stringstream >> out中的in和out都是string,那么如果in里含有空格,则out就会在空格这里截断,应该是stringstream的问题,不知道为什么会这样,所以后面给类做了特化。

对于相同类型,不进行额外转化。


以下是头文件

lexical_cast.h

#ifndef LEXICAL_CAST_H
#define LEXICAL_CAST_H

#include <sstream>
#include <typeinfo> //bad_cast

namespace lexical {

class bad_cast : public std::bad_cast
{
public:
	virtual const char* what() const throw()
	{
		return "bad lexical cast: source type value could not be interpreted as target";
	}
};

template<typename Target>
struct  cast_to {
	template<typename Source>
	static Target from(const Source& in) {
		static std::stringstream s;
		s.clear();
		s.str("");
		Target result;
		if ((s << in).fail() || (s >> result).fail())
			throw bad_cast();
		return result;
	}
	static Target from(const Target& in) {
		return in;
	}
};


template<>
struct cast_to<std::string> {
	template<typename Source>
	static std::string from(const Source& in) {
		static std::stringstream s;
		s.clear();
		s.str("");
		if ((s << in).fail())
			throw bad_cast();
		return s.str();
	}
	static std::string from(const std::string& in) {
		return in;
	}
};

}

#endif //LEXICAL_CAST_H




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值