iostream 的 C++ 包装器类,使用流修饰符,如 std::endl 和 operator<<

标签 c++ stl wrapper iostream

<分区>

我目前正在为 std::stringstream 编写包装器我想转发所有operator<<通过我的类(class)调用std::stringstream .这现在工作得很好 (感谢这个问题:wrapper class for STL stream: forward operator<< calls),但它仍然存在一个问题。

假设我有以下代码:

class StreamWrapper {
private:
    std::stringstream buffer;
public:
    template<typename T>
    void write(T &t);

    template<typename T>
    friend StreamWrapper& operator<<(StreamWrapper& o, T const& t);

    // other stuff ...
};


template<typename T>
StreamWrapper& operator<<(StreamWrapper& o, T const& t) {
    o.write(t);
    return o;
}

template<typename T>
void StreamWrapper::write(T& t) {
    // other stuff ...

    buffer << t;

    // other stuff ...
}

如果我现在这样做:

StreamWrapper wrapper;
wrapper << "text" << 15 << "stuff";

这很好用。但是如果我想使用像 std::endl 这样的流修饰符, 这是一个根据 http://www.cplusplus.com/reference/ios/endl 的函数,我就是不编译。

StreamWrapper wrapper;
wrapper << "text" << 15 << "stuff" << std::endl;

为什么?我如何也转发流修饰符?

最佳答案

参见 this answer .

你会想要

typedef std::ostream& (*STRFUNC)(std::ostream&);

StreamWrapper& operator<<(STRFUNC func)  // as a member, othewise you need the additional StreamWrappe& argument first
{
  this->write(func);
  return *this;
}

关于iostream 的 C++ 包装器类,使用流修饰符,如 std::endl 和 operator<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14829770/

相关文章:

c++ - stringstream->rdbuf()->pubsetbuf 没有设置缓冲区

Android NDK 如何将收到的 DatagramPacket 作为参数传递给 C 函数?

c++ - `iterators` 和 `references to elements` 之间的区别

c++ - 在 Windows 的 C++ 中使用 recvfrom() 时出现 WSAEFAULT 错误

c++ - std::make_shared、std::unique_ptr 和移动构造函数

c# - C#、C++ 和 C 的混合

c# - 系统.AccessViolationException :Attempted to read or write protected memory

c# - 如何根据时间或百分比剪切/裁剪/修剪视频并将输出保存在不同的文件中

c++ - 为什么 Clang 决定允许在 C++ 中指定初始化器?

C++ 多线程性能比单线程代码慢