启用与boost::lexical_cast一起使用的类

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> Source是可输出流

3> Target是可输入流

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

问题2> 为什么上述代码中operator<<operator>>的返回值不是对std :: ostream&std :: istream&的引用?


代码不返回引用很可能是一个错误,因为流是不可复制的。 - Xeo
lexical_castable::read_ 是一个常量成员函数是一个错误。 - q0987
lexical_castable::print 包含一个 '\n' 是一个 bug。 - q0987
1个回答

8
为了让你的类能够与lexical_cast一起使用,只需为其定义“流”操作符。 来自Boost.LexicalCast概述
  • 源是OutputStreamable,意味着定义了一个operator<<,该操作符将左侧是std::ostreamstd::wostream对象,右侧是参数类型实例。
  • 目标是InputStreamable,意味着定义了一个operator>>,该操作符将左侧是std::istreamstd::wistream对象,右侧是结果类型实例。
  • 目标是CopyConstructible [20.1.3]。
  • 目标是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>>也是同样的道理。

OP正在询问如何在不使用字符串流的情况下处理一些类型的lexical_cast。 - Kos
@Kos:原帖问的是他是否必须一直使用字符串。 - Xeo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接