What type of function is endl? How to define something like endl?

Im new for C ++, so endl is used to end the line as

cout << "Hello" << endl; 

My research on the Internet tells me that this is a function, if so, why we can call it without using "();"

How to declare such a function, suppose I want to make a function that just picks up the console every time I ask for input like

 string ain() { return " : ?"; } 

now instead of using it every time like this

 cout << "Whats your name " << ain(); 

I want to use it as

 cout << "Question " << ain; 

Just like endl, I know that "()" is not so much, and in fact it does nothing huge to save a ton of load time, but I basically ask this question to find out why endl can do this to do.

+5
source share
2 answers

According to cppreference endl is a function template with the following prototype:

 template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os ); 

std::ostream operator<< overloaded to call it when it sees it.

You can define a similar template yourself:

 template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& foo( std::basic_ostream<CharT, Traits>& os ) { return os << "foo!"; } 

Now doing

 cout << foo << endl; 

Print foo! to standard output.

+9
source

std::ostream has function overload function

 std::ostream& operator<<(std::ostream& (*func)(std::ostream&)); 

That means you can use

 std::cout << ain; 

if ain declared as:

 std::ostream& ain(std::ostream& out); 

Its implementation will be something like this:

 std::ostream& ain(std::ostream& out) { return (out << " : ?"); } 
+4
source

Source: https://habr.com/ru/post/1258444/


All Articles