Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload operator << to act like what ostream does

I am on implementing a class, and I'd like to pass some parameters to the instance using <<.

For example,

terminal term;
term << "Hello World!" << '\n';

The code goes below,

class terminal {
    template <typename T>
    terminal& operator << (T& t) {
        std::cout << t;
        return *this;
    }
};

Basically, I'd like to be a stream instead of being the part of stream. (not cout << term;)

(Sorry for that I forgot to specify my question) The question is, it worked well with strings, but it compiled failed if there is a number (like int, char, etc).

If we use the example above, the compiler will complain that

Invalid operands to binary expression ('terminal' and 'int')

like image 414
0xBBC Avatar asked Jan 27 '26 20:01

0xBBC


1 Answers

I would change to the following, in order for sequencing of operator<< (e.g., term << "hello" << std::endl; ) to work:

namespace foo {

class terminal {    
  std::ostream &strm;
public:
  terminal(std::ostream &strm_) : strm(strm_) {}
  terminal() : strm(std::cout) {}

  template <typename T>
  friend std::ostream& operator<<(terminal &term, T const &t);
};

template <typename T>
std::ostream& operator<<(terminal &term, T const &t) {
  term.strm << t;
  return term.strm;
}

}

Live Demo

like image 198
101010 Avatar answered Jan 30 '26 10:01

101010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!