用于iostream的C++包装器类,使用带有operator <<的std :: endl等流修饰符

Mar*_*ant 5 c++ iostream stl wrapper

我正在为a编写一个包装器std::stringstream,我希望operator<<通过我的类将所有调用转发给std::stringstream.现在这很好用(感谢这个问题:STL流的包装类:前向运算符<<调用),但它仍有一个问题.

假设我有以下代码:

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 ...
}
Run Code Online (Sandbox Code Playgroud)

如果我现在这样做:

StreamWrapper wrapper;
wrapper << "text" << 15 << "stuff";
Run Code Online (Sandbox Code Playgroud)

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

StreamWrapper wrapper;
wrapper << "text" << 15 << "stuff" << std::endl;
Run Code Online (Sandbox Code Playgroud)

为什么?我怎样才能转发流修改器呢?

rub*_*nvb 3

看到这个答案

你会想要

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;
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

2671 次

最近记录:

12 年,11 月 前