本文介绍了mycout自动结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现类 MyCout ,它可以提供自动endl的可能性,即此代码

I'd like implement class MyCout, which can provide possibility of automatic endl, i.e. this code

MyCout mycout;
mycout<<1<<2<<3;

输出

123
//empty line here

是否可以用这样的功能?

Is it possible to implement class with such functionality?

更新:
解决方案不应该像 MyCout( )<< 1< 2<< 3; ,即它们应该没有创建临时对象

UPDATE:Soulutions shouldn't be like that MyCout()<<1<<2<<3; i.e. they should be without creating temporary object

推荐答案

这只是的一种变体,它不使用堆。

This is simply a variant of Rob's answer, that doesn't use the heap. It's a big enough change that I didn't want to just change his answer though

struct MyCout {
  MyCout(std::ostream& os = std::cout) : os(os) {}
  struct A {
    A(std::ostream& r) : os(r), live(true) {}
    A(A& r) : os(r.os), live(true) {r.live=false;}
    A(A&& r) : os(r.os), live(true) {r.live=false;}
    ~A() { if(live) {os << std::endl;} }
    std::ostream& os;
    bool live;
  };
  std::ostream& os;
};

template <class T>
MyCout::A operator<<(MyCout::A&& a, const T& t) {
  a.os << t;
  return a;
}

template<class T>
MyCout::A operator<<(MyCout& m, const T& t) { return MyCout::A(m.os) << t; }

int main () {
  MyCout mycout;
  mycout << 1 << 2.0 << '3';
  mycout << 3 << 4.0 << '5';
  MyCout mycerr(std::cerr);
  mycerr << 6 << "Hello, world" << "!";
}

这篇关于mycout自动结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 07:48