简体   繁体   中英

User-defined Output Stream Manipulators in C

I am learning C++, and in the part of user-defined output stream manipulatior, I am stuck. This is the example code:

    #include <iostream>
     using std::cout;
     using std::flush;
     using std::ostream;

    ostream& endLine( ostream& output )
    {
      return output << '\n' << flush;
    }

    int main()
    {
       cout << "Testing:" << endLine;
       return 0;
    }

My question is, in the definition of endLine, there is an argument. But in the main function, why it is endLine only without brackets and according arguments.

std::basic_ostream has several overloads of operator<< , one of which has the following signature:

 basic_ostream& operator<<( basic_ostream& st, std::basic_ostream& (*func)(std::basic_ostream&) ); 

That is, this function takes a pointer to a function that both takes and returns std::ios_base . The method is called by this function and is incorporated into the input/output operation. Thereby making this possible:

std::cout << endLine;

So what will happen is that endLine is converted into a function pointer and a new line character will be written to the stream and afterwards a flush operation.

std::ostream has an overload of operator<< that takes a pointer to a function (or something similar that can be invoked, anyway) that accepts the pointer, and invokes the function, passing itself as a parameter to the function:

std::ostream &operator<<(std::ostream &os, ostream &(*f)(ostream &os)) { 
    return f(*this);
}

The version that's built in to ostream comes from std::ios_base (and that's the type it uses for the parameter and return), but if you're trying to write your own, you typically want to use std::ostream instead.

cout 's left shift operator calls endLine with cout as an argument. Functions (technically function pointers) don't need to be called when you write their names; you can pass them around as values and have some other code call them later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM