lexical_cast的代码段:
class lexical_castable { public: lexical_castable() {}; lexical_castable(const std::string s) : s_(s) {}; friend std::ostream operator<< (std::ostream& o,const lexical_castable& le); friend std::istream operator>> (std::istream& i,lexical_castable& le); private: virtual void print_(std::ostream& o) const { o << s_ <<"\n"; } virtual void read_(std::istream& i) const { i >> s_; } std::string s_; }; std::ostream operator<<(std::ostream& o,const lexical_castable& le) { le.print_(o); return o; } std::istream operator>>(std::istream& i,lexical_castable& le) { le.read_(i); return i; }
基于document,
template<typename Target,typename Source> Target lexical_cast(const Source& arg);
1> Returns the result of streaming arg into a standard library
string-based stream and then out as a Target object.2> Source is OutputStreamable
3> Target is InputStreamable
问题1>对于用户定义类型(UDT),OutputStreamable或InputStreamable是否总是必须处理std :: string?例如,给定一个包含一个简单整数作为成员变量的类,当我们定义运算符<<和运算符>>,实现代码是什么样的?我必须将整数转换为字符串吗?根据我的理解,似乎UDT总是必须处理std :: string才能使用boost :: lexical_cast和boost :: lexcial_cast需要中间std :: string来进行真正的转换作业.
问题2>为什么运算符的返回值<<或运算符>>在上面的代码中没有引用std :: ostream&或std :: istream&分别?
解决方法
要使您的类可用于lexical_cast,只需为其定义“stream”运算符即可.
从 Boost.LexicalCast Synopsis开始:
从 Boost.LexicalCast Synopsis开始:
- Source is OutputStreamable,meaning that an
operator<<
is defined that takes astd::ostream
orstd::wostream
object on the left hand side and an instance of the argument type on the right.- Target is InputStreamable,meaning that an
operator>>
is defined that takes astd::istream
orstd::wistream
object on the left hand side and an instance of the result type on the right.- Target is CopyConstructible [20.1.3].
- Target is DefaultConstructible,meaning that it is possible to default-initialize an object of that type [8.5,20.1.4].
:
// either inline friend,out-of-class friend,or just normal free function // depending on whether it needs to access internel members // or can cope with the public interface // (use only one version) class MyClass{ int _i; public: // inline version friend std::ostream& operator<<(std::ostream& os,MyClass const& ms){ return os << ms._i; } // or out-of-class friend (friend declaration inside class only) friend std::ostream& operator<<(std::ostream& os,MyClass const& ms); // for the free function version int get_i() const{ return _i; } }; // out-of-class continued std::ostream& operator<<(std::ostream& os,MyClass const& ms){ return os << ms._i; } // free function,non-friend std::ostream& operator<<(std::ostream& os,MyClass const& ms){ return os << ms.get_i(); }
对于操作符>>当然也是如此.