Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 891
Zeenobit Avatar asked Oct 02 '11 00:10

Zeenobit


People also ask

Is Endl a function C++?

C++ manipulator endl function is used to insert a new line character and flush the stream. Working of endl manipulator is similar to '\n' character in C++.

What is the point of std :: endl?

std::endl. Inserts a new-line character and flushes the stream. Its behavior is equivalent to calling os.

Is std :: endl necessary?

There is rarely a need for std::endl , and getting in the habit of using it will lead to mysteriously slow code. Just use '\n' unless you know you need to flush the buffer.

Should I use std :: endl or \n?

Both endl and \n serve the same purpose in C++ – they insert a new line. However, the key difference between them is that endl causes a flushing of the output buffer every time it is called, whereas \n does not.


2 Answers

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.

like image 196
CB Bailey Avatar answered Sep 30 '22 17:09

CB Bailey


Though it's a function [template], standard stream manipulators are designed to be sent to streams as function pointers (or functor object references). Inserting the result of a function call won't give you anything but the value that results from that function call.

This means that you stream the functor itself (f), rather than the result of calling it (f()).

like image 41
Lightness Races in Orbit Avatar answered Sep 30 '22 19:09

Lightness Races in Orbit