[c++] How to properly overload the << operator for an ostream?

In C++14 you can use the following template to print any object which has a T::print(std::ostream&)const; member.

template<class T>
auto operator<<(std::ostream& os, T const & t) -> decltype(t.print(os), os) 
{ 
    t.print(os); 
    return os; 
} 

In C++20 Concepts can be used.

template<typename T>
concept Printable = requires(std::ostream& os, T const & t) {
    { t.print(os) };
};

template<Printable T>
std::ostream& operator<<(std::ostream& os, const T& t) { 
    t.print(os); 
    return os; 
} 

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to namespaces

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model How do I get an object's unqualified (short) class name? socket.error:[errno 99] cannot assign requested address and namespace in python What is the use of "using namespace std"? Visibility of global variables in imported modules Using :: in C++ 'namespace' but is used like a 'type' type object 'datetime.datetime' has no attribute 'datetime' Why am I getting error CS0246: The type or namespace name could not be found? string in namespace std does not name a type

Examples related to operator-overloading

Operator overloading ==, !=, Equals operator << must take exactly one argument assignment operator overloading in c++ What are the basic rules and idioms for operator overloading? Operator overloading on class templates How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers How to override the [] operator in Python? Operator overloading in Java How to properly overload the << operator for an ostream? How do I overload the [] operator in C#

Examples related to iostream

'cout' was not declared in this scope How to read line by line or a whole text file at once? How to print Unicode character in C++? Why std::cout instead of simply cout? operator << must take exactly one argument How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT? Why is reading lines from stdin much slower in C++ than Python? How to print (using cout) a number in binary form? Why would we call cin.clear() and cin.ignore() after reading input? Reading a file character by character in C

Examples related to ostream

how do I print an unsigned char as hex in c++ using ostream? How to properly overload the << operator for an ostream?