编写一个像"std :: cout"一样工作的简单函数,但在结尾添加一个换行符

dan*_*jar 0 c++ stl cout function stream

在C++中有一个名为的标准库函数cout,它允许我将文本发送到控制台.我相信你知道的.

#include <iostream>
using std::cout;
cout << "Some Text " << 15 << " Other Text";
Run Code Online (Sandbox Code Playgroud)

要在最后做一个换行,我需要使用endl.

cout << "Some Text " << 15 << " Other Text" << endl;
Run Code Online (Sandbox Code Playgroud)

我怎样才能编写一个coutl行为相似的函数,cout但也添加了一个像?我想使用与使用相同的语法cout,尤其是<<运算符.

coutl << "Some Text " << 15 << " Other Text"; // coutl should add a linebreak
Run Code Online (Sandbox Code Playgroud)

mau*_*uve 6

通过创建一个<< endl在其析构函数中添加的小代理对象:

class AddEndl
{
public:
  AddEndl(std::ostream& os) : _holder(new Holder(os)) {}

  template <class T>
  friend std::ostream& operator<< (const AddEndl& l, const T& t)
  {
    return (l._holder->_os) << t;
  }

private:
  struct Holder {
    Holder (std::ostream& os) : _os(os) {}
    ~Holder () { _os << std::endl; }

    std::ostream& _os;
  };

  mutable std::shared_ptr<Holder> _holder;
}
Run Code Online (Sandbox Code Playgroud)

然后你需要一个函数,以便你得到一个临时的:

AddEndl wrap(std::ostream& os)
{
  return AddEndl(os);
}
Run Code Online (Sandbox Code Playgroud)

这应该工作:

wrap(std::cout) << "Hello";
Run Code Online (Sandbox Code Playgroud)

更新:

我移动析构函数,它将一个std::endl内部对象添加到a所拥有的内部对象,std::shared_ptr<>以便该示例不再依赖于Copy Elision.