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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With