gpt4 book ai didi

c++ - 启用用于 boost::lexical_cast 的类

转载 作者:可可西里 更新时间:2023-11-01 17:52:24 26 4
gpt4 key购买 nike

来自 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? ?例如,给定一个包含简单整数作为成员变量的类,当我们定义 operator<< 时和 operator>> ,实现代码是什么样的?我必须将整数转换为字符串吗?根据我的理解,似乎UDT总是要处理std::string为了与boost::lexical_cast一起工作和 boost::lexcial_cast需要中间体std::string做真正的转换工作。

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

最佳答案

使您的类(class)可用于 lexical_cast ,只需为其定义“流”运算符。来自 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();
}

对于operator>>当然是一样的.

关于c++ - 启用用于 boost::lexical_cast 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8630451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com