Why does endl(std::cout) compile

后端 未结 2 1037
执念已碎
执念已碎 2021-02-02 00:44

Surprisingly the below code compiles and runs without error on a variety of compilers and versions.

#include 

int main() {
    endl(std::cout);
         


        
2条回答
  •  走了就别回头了
    2021-02-02 01:05

    It is the way the stream manipulators work. Manipulators are functions that passed to operator << as arguments. Then within the operator they are simply called.

    So you have function declared like

    template 
    basic_ostream& endl(basic_ostream& os);
    

    and you pass its pointer to operator <<. And inside the operator that declared something like

    ostream& ostream::operator << ( ostream& (*op)(ostream&));
    

    the function is called.like

    return (*endl )(*this);
    

    Thus when you see record

    std::cout << std::endl;
    

    then std::endl is function pointer that is passed to the operator << as argument.

    In the record

    std::endl( std::cout );
    

    namespace prefix before name endl may be omitted because in this case the compiler will use the Argument Dependent Lookup. Thus this record

    endl( std::cout );
    

    will compile successfully.

    However if to enclose the function name in parentheses then ADL is not used and the following record

    ( endl )( std::cout );
    

    will not compiled.

提交回复
热议问题