Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

c++ - How does std::endl not use any brackets if it is a function?

The question is pretty much in the title. According to C++ Reference, std::endl is actually a function. Looking at its declaration in <iostream>, this can be verified.

However, when you use std::endl, you don't use std::endl(). Instead, you use:

std::cout << "Foo" << std::endl;

In fact, if you use std::endl(), the compiler demands more parameters, as noted on the link above.

Would someone care to explain this? What is so special about std::endl? Can we implement functions that do not require any brackets when calling too?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

std::endl is a function template declared (27.7.3.8):

template <class charT, class traits>
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);

The reason that you can "stream" it to std::cout is that the basic_ostream class template has a member declared:

basic_ostream<charT,traits>& operator<<
    ( basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&) );

which is defined to have the effect of returning pf(*this) (27.7.3.6.3).

std::endl without parentheses refers to a set of overload functions - all possible specializations of the function template, but used in a context where a function pointer of one particular type is acceptable (i.e. as an argument to operator<<), the correct specialization can be unambiguously deduced.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...