c – 启用类以与boost :: lexical_cast一起使用

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开始:
  • Source is OutputStreamable,meaning that an operator<< is defined that takes a std::ostream or std::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 a std::istream or std::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();
}

对于操作符>>当然也是如此.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...