【问题标题】:Enabling Classes for Use with boost::lexical_cast启用与 boost::lexical_cast 一起使用的类
【发布时间】:2011-12-25 16:30:01
【问题描述】:

来自lexical_cast的代码sn-p:

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> 将流式 arg 的结果返回到标准库中 基于字符串的流,然后作为 Target 对象输出。

2> 源是 OutputStreamable

3> 目标是 InputStreamable

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

问题2> 为什么上面代码中operator&lt;&lt;或operator&gt;&gt;的返回值没有分别引用std::ostream&amp;或std::istream&amp;?

【问题讨论】:

  • 代码不返回引用很可能是一个错误,因为流不可复制。
  • lexical_castable::read_是const成员函数是个bug
  • lexical_castable::print 包含 '\n' 是一个错误。

标签: c++ boost lexical-cast


【解决方案1】:

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

  • Source 是 OutputStreamable,这意味着定义了一个 operator&lt;&lt;,它采用左侧的 std::ostream 或 std::wostream 对象手边和右边的参数类型的实例。
  • Target 是 InputStreamable,这意味着定义了一个 operator&gt;&gt;,它采用左侧的 std::istream 或 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&gt;&gt; 当然也一样。

【讨论】:

  • OP 询问如何处理某些类型的 lexical_cast 没有中间的字符串流。
  • @Kos:OP 询问他是否必须一直使用 strings。
猜你喜欢
  • 2011-09-14
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
相关资源
最近更新 更多