c++ - 为自定义流类设置 std::io_base 标志

标签 c++ iostream cout flags ostringstream

我有一个名为 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 所以它应该调用它并设置流的标志。但它总是调用模板。注意:如果我删除此模板,一切都会像您期望的那样正常工作,但有没有办法同时拥有这两者?

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

最佳答案

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

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

关于c++ - 为自定义流类设置 std::io_base 标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16025364/

相关文章:

c++ - 这两者的区别?

c++ - cin不接受C++中带有空格的输入吗?

c++ - 在 C++ std::streams 中,失败后,如何获取失败原因?必需:线程安全且 Windows 和 Linux 通用(或至少 Msvc/Gcc)

C++ 将区域设置全局重置为 "C"?

c++ - C++ 中的流使程序崩溃

c++ - 参数和全局变量,菜单程序

c++ - 为什么我们在Qt中处理表单时要为ui对象声明一个命名空间?

c++ - 同一命令的多个手册页之间有什么区别?

c++ - 如何在 C++ 中获取以下输入

c++ - 为什么我不能使用 cout 在 C++ 中打印字符串值数组?