C++ overloads the << operator for output (so you can say std::cout << 42 << std::endl;) and the >> operator for input (so you can say std::cin >> x >> y). What's this weird directionality doing there? Why can't I say 42 >> std::cout, when outputting a lot of stuff, to emphasise the value I'm writing, rather than where to I'm writing?

Well, we don't have to settle for this! We can use template functions to "fix" this...

template<typename OT> ostream&
operator>>(const T& val, ostream& out) {
  return out << val;
}
(and similarly for operator<< for input).

Why not?

While C++ lets you overload your operators (which is how we got into this fine mess to start off with!), it doesn't let you change their associativity (or their precedence, but that's not a problem here). So a>>b>>c is always (a>>b)>>c.

Which means that if we were foolish enough to use the above definition of >> for output, 42 >> std::cout would work, but endl >> 42 >> std::cout would be a (compile time) error, and 43 >> 42 >> std::cout would be correct C++, but give an entirely wrong result (in this case, it would write "" to std::cout, which was probably not what we'd expect).

The << syntax was probably taken from the here document construct in Unix shells:

#!/bin/sh
cat << ZZ
hello
world
ZZ

will print

hello
world

The >> construct also exists, but its meaning has nothing to do with the C++ operator.

Log in or registerto write something here or to contact authors.