December 2018
Intermediate to advanced
552 pages
12h 18m
English
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.outNo such ...Read now
Unlock full access