C++ streams provide the ability to overload the << and >> operators for user-defined types. This provides the ability to create custom, type-safe IO for any data type, including system-level data types, structures, and even more complicated types such as classes. For example, the following provides an overload for the << stream operator to print an error code provided by a POSIX-style function:
#include <fcntl.h>
#include <string.h>
#include <iostream>
class custom_errno
{ };
std::ostream &operator<<(std::ostream &os, const custom_errno &e)
{ return os << strerror(errno); }
int main()
{
if (open("filename.txt", O_RDWR) == -1) {
std::cout << custom_errno{} << '\n';
}
}
> g++ -std=c++17 scratchpad.cpp; ./a.out
No such file or directory
In this example...