CKTIS / C++
Stream insertion operator <<
The << operator writes values to an output stream. Learn the distinction between member overloads and non-member functions, and how to support a custom type while preserving chained insertion.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
stream << value;
stream << first << second;
std::ostream& operator<<(std::ostream& os, const T& value);The expression stream << value selects an output-stream insertion overload. std::ostream is an alias for std::basic_ostream<char>. The symbol std::ostream::operator<< denotes member overloads, including those for numbers and manipulator function pointers. Here, operator<<(std::ostream&, ...) denotes a family of non-member functions, not a variadic function declaration: ... is a descriptive placeholder for further parameters. Standard overloads for characters and null-terminated strings are non-member functions.
The overloads used in the example return a reference to the same stream, so stream << first << second works as (stream << first) << second. Insertion does not automatically add spaces or a newline. Explicitly calling stream.operator<<('A') bypasses the non-member character overloads and selects a numeric overload instead of printing the character.
For a custom type, define a non-member std::ostream& operator<<(std::ostream& os, const T& value) in the same namespace as the type, not in std. Return os, usually by returning the complete insertion expression. The example applies this pattern to Point and explicitly appends \n.
Output depends on the stream's formatting state; for example, manipulators can change numeric formatting. Returning a reference does not confirm successful output: check the stream state, as the example does. The supplied sources are the current standard draft, not a frozen C++23 text; a local build with a C++23 flag does not establish production-runtime compatibility.
Examples
#include <iostream>
struct Point {
int x;
int y;
};
std::ostream& operator<<(std::ostream& os, const Point& point) {
return os << '(' << point.x << ", " << point.y << ')';
}
int main() {
const Point point{2, 3};
std::cout << "Point: " << point << '\n';
return std::cout ? 0 : 1;
}
Result
Point: (2, 3)
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.