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

前端之家收集整理的这篇文章主要介绍了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/117881.html

猜你在找的C&C++相关文章