8

来自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;
}

根据文件

template<typename Target, typename Source>
  Target lexical_cast(const Source& arg);

1> 将流式 arg 的结果返回到基于标准库字符串的流中,然后作为 Target 对象输出。

2> 源是OutputStreamable

3> 目标是 InputStreamable

Question1 > 对于用户定义类型(UDT),OutputStreamable 或 InputStreamable 是否总是需要处理std::string?例如,给定一个包含一个简单整数作为成员变量的类,当我们定义operator<<and时operator>>,实现代码是什么样的?我必须将整数转换为字符串吗?根据我的理解,UDT 似乎总是必须处理std::string才能与之合作,boost::lexical_cast并且boost::lexcial_cast需要中间体std::string来完成真正的转换工作。

Question2 > 为什么上面代码中operator<<or的返回值operator>>没有分别引用std::ostream&or std::istream&

4

1 回答 1

8

要使您的类可用于lexical_cast,只需为其定义“流”运算符。来自Boost.LexicalCast 概要

  • Source 是 OutputStreamable,这意味着operator<<定义的an在左侧 采用std::ostreamor对象,在右侧采用参数类型的实例。std::wostream
  • Target 是 InputStreamable,这意味着operator>>定义的an在左侧 采用std::istreamor对象,在右侧采用结果类型的实例。std::wistream
  • 目标是 CopyConstructible [20.1.3]。
  • Target 是 DefaultConstructible,这意味着可以默认初始化该类型的对象 [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();
}

当然对于operator>>.

于 2011-12-25T16:41:03.090 回答