C++ Bit shift operators for I/O


Example

The operators << and >> are commonly used as "write" and "read" operators:

  • std::ostream overloads << to write variables to the underlying stream (example: std::cout)
  • std::istream overloads >> to read from the underlying stream to a variable (example: std::cin)

The way they do this is similar if you wanted to overload them "normally" outside of the class/struct, except that specifying the arguments are not of the same type:

  • Return type is the stream you want to overload from (for example, std::ostream) passed by reference, to allow chaining (Chaining: std::cout << a << b;). Example: std::ostream&
  • lhs would be the same as the return type
  • rhs is the type you want to allow overloading from (i.e. T), passed by const& instead of value for performance reason (rhs shouldn't be changed anyway). Example: const Vector&.

Example:

//Overload std::ostream operator<< to allow output from Vector's
std::ostream& operator<<(std::ostream& lhs, const Vector& rhs)
{
    lhs << "x: " << rhs.x << " y: " << rhs.y << " z: " << rhs.z << '\n';
    return lhs;
}

Vector v = { 1, 2, 3};

//Now you can do
std::cout << v;