本文介绍了写一个简单的函数,其工作原理类似于“std :: cout”但在结束处添加换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In C++ there is a standard library function called cout, which lets me send text to the console. I am sure you know that.

#include <iostream>
using std::cout;
cout << "Some Text " << 15 << " Other Text";

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

To do a linebreak at the end, I need to use endl.

cout << "Some Text " << 15 << " Other Text" << endl;



cout
,但也添加了一个likebreak?我想使用 cout 使用的相同语法,特别是<< 运算符。

How can I write a function named coutl which behaves like cout but also adds a likebreak? I want to use the same syntax that cout uses, especially the << operator.

coutl << "Some Text " << 15 << " Other Text"; // coutl should add a linebreak


推荐答案

代理对象,它添加<< endl 在其析构函数中:

By creating a little proxy object which adds << endl in its destructor:

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;
}

然后你需要一个函数, >

Then you need a function so that you will get a temporary:

AddEndl wrap(std::ostream& os)
{
  return AddEndl(os);
}

这应该可以工作:

wrap(std::cout) << "Hello";

UPDATE:

我移动析构函数,它向 std :: shared_ptr<> std :: endl c $ c>,使示例不再依赖于复制Elision。

I move the destructor which adds a std::endl to an inner object owned by a std::shared_ptr<> so that the example doesn't depend on Copy Elision anymore.

这篇关于写一个简单的函数,其工作原理类似于“std :: cout”但在结束处添加换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:48