#include // Understanding the details demonstrated in this example is // not required for a first-year programming course. This // example is provided for students who are curious about why // expressions such as // // std::cout << std::endl; // // actually work. // // In particular, std::endl is a function. The C++ standard // library allows a function with the appropriate parameter // and return type to appear on the right-hand side of the // stream insertion operator <<. // // We will define our own function, 'inspection', that has the // same relevant form as std::endl. int main(); std::ostream &inspection( std::ostream &out ); // Function definitions int main() { std::cout << inspection << std::endl; return 0; } // For a function such as 'inspection' to be used in this way, // it must have the appropriate parameter and return types: // // std::ostream &inspection( std::ostream &out ) // // That is, it // - takes a reference to a std::ostream object as an argument, // and // - returns a reference to the std::ostream object that was // passed. // // When the compiler encounters // // std::cout << inspection; // // there is a version of operator<< that accepts a function // having this form. Rather than printing the function, // operator<< calls the function and passes std::cout to it. // // Thus, // // std::cout << inspection; // // effectively results in // // inspection( std::cout ); // // The function then performs whatever operations it wishes // on the stream and returns that stream. Returning the stream // allows further uses of << to be chained onto the expression. // // This is also essentially how // // std::cout << std::endl; // // works. The function std::endl is passed the output stream, // writes a newline character, flushes the stream, and returns // the stream. // // Exercises: // 1. Replace the body of 'inspection' with // // return out << "Kilroy was here..."; // // Does it still work? For this to work, what must the // return value of // // out << "Kilroy was here..." // // be? // // 2. Replace // // std::cout << inspection << std::endl; // // with // // inspection( std::cout ); // std::endl( std::cout ); // // Does it still work? // // If you did this in ordinary C++ code, do you think that // other programmers would be // // a. impressed with your intimate knowledge of the // implementation of the C++ standard library, or // // b. really annoyed that you are not following the // conventional usage? // // If your answer is 'a', please visit // // https://welcome.uwo.ca/admissions/ // // for further details concerning your academic future. :-) std::ostream &inspection( std::ostream &out ) { out << "Kilroy was here..."; return out; }