用法:
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