【问题标题】:Setting std::io_base flags for custom stream class为自定义流类设置 std::io_base 标志
【发布时间】:2013-04-08 04:02:44
【问题描述】:

我有一个名为 Stream 的自定义类

class Stream
public:
    Stream& operator<<(int i) { stream_ << i; return *this;}
            template <typename CustomClass>
            Stream& operator<<(const CustomClass& c) { stream_ << c.toString() /* assume this template always have toString(); return *this; }
private:
    std::stringstream stream_;
};

这是我实际拥有的一个非常基本的示例。我正在尝试设置 std::ios_base 标志,如下所示:

Stream() << 1 << std::hex << 2;

使用运算符;

Stream& operator<<(std::ios_base& b) { stream_.setf(b.flags()); return *this; }

据我了解,因为 std::hex 返回 std::ios_base 所以它应该调用它并设置流的标志。但它总是调用模板。注意:如果我删除此模板,一切都会如您所愿,但有没有办法同时拥有这两者?

如果您需要更多说明,请随时进一步询问

【问题讨论】:

  • 只是为了澄清一点,我正在尝试使 ios_base 重载运算符 !important 超过模板。我相信这是非常奇怪的行为,因为如果在编译时没有其他类型可以解决,那么模板应该放在最后,应该使用它。我相信 std 库是在所有其他库之前链接的。
  • 顺便说一句,即使我返回 std::ios_base&amp; 并返回流,这也不起作用,我的意思是它仍然通过类型化重载调用模板

标签: c++ iostream cout flags ostringstream


【解决方案1】:

IOStream 操纵器不是std::ios_base 类型的对象,它们是接受和返回std::ios_base 引用的函数。所以当你想对这些对象进行流插入时,你必须为函数指针重载:

Stream& operator<<(std::ios_base& (*manip)(std::ios_base&))
//                 ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
{
    manip(this->stream);
    return *this;
}

【讨论】:

    猜你喜欢
    • 2021-04-23
    • 2011-01-12
    • 2012-03-05
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多