Bit shift operators for IO
suggest changeThe operators << and >> are commonly used as “write” and “read” operators:
std::ostreamoverloads<<to write variables to the underlying stream (example:std::cout)std::istreamoverloads>>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& lhswould be the same as the return typerhsis the type you want to allow overloading from (i.e.T), passed byconst&instead of value for performance reason (rhsshouldn’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;
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents