Structure std :: endl

I am new to C ++ and I am confused about std::endl . When you are trying to understand what std::endl , I came across some resources that told me that this is a function.

However, how can a function be stripped of parentheses?

+7
c ++ c ++ - standard-library endl
source share
3 answers

However, how can a function be stripped of parentheses?

A function name not followed by () is just a reference to that function. This is exactly the same as with any other type:

 void foo(int) {} char x = 'a'; char *p = &x; int main() { p; // Refers to p *p; // Dereferences p (refers to whatever p points to) foo; // Refers to foo foo(42); // Calls foo } 

std::endl is a function (actually a function template) that takes a single parameter of type "stream" and works by inserting an EOL representation into this stream and then flushing it. You can use it like any other function if you want:

 std::endl(std::cout); 

The last part of the puzzle is that the standard library provides an overload (again, a pattern) of operator << , so the LHS argument is a stream, and the RHS argument is a function; the implementation of this operator calls the RHS argument (function) and passes it to the LHS (stream). Understandably, something like this:

 Stream& operator<< (Stream &s, const Function &f) { f(s); return s; } 

Therefore, calling std::cout << std::endl causes this operator overload, which in turn calls std::endl(std::cout) , which inserts EOL + flushing.

As for the preferred form (direct call against the << operator), this is definitely the use of << . This is idiomatic, and it makes it easy to compose multiple stream manipulators within a single expression. Like this:

 std::cout << "Temperature: " << std::fixed << std::setprecision(3) << temperature << " (rounds to " << std::setprecision(1) << temperature << ')' << std::endl; 
+4
source share

Read the ref :

std::endl

Inserts a newline and clears the stream.

Used with a stream, for example std::cout .

This is not a function, this is a function template.

std::endl without parentheses refers to a set of overload functions - all kinds of specializations of this function template. More details in How does std :: endl not use any brackets if it is a function?

+6
source share

endl is an input-output manipulator for output only.

endl is an input-output manipulator for output only, it can be called with an expression of type out << std::endl for any type of std::basic_ostream .

Inserts a newline into the os output sequence and discards it as if it were calling os.put(os.widen('\n')) and then os.flush() .

0
source share

All Articles