What type of a function is endl? How do I define something like endl?
c++, function, iostream
Solution
As per 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`'s `operator<<` is overloaded to call it upon seeing 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, executing
cout << foo << endl;
Will print foo! to the standard output.
Problem
Im new to C++, So the endl is used to end the line as ``` cout << "Hello" << endl; ``` My research around the web tells me it's a function, if it is so why can we call it without using the "();" How do I declare a function like that, let us suppose I want to make a function that just tidies up the console everytime I ask for input as ``` string ain() { return " : ?"; } ``` now instead of having to use this everytime like this ``` cout << "Whats your name " << ain(); ``` I want to be able to use it as ``` cout << "Question " << ain; ``` Just as endl is, I know "()" is not much and this doesn't really do anything huge to save a ton load of time, but im basically asking this question to figure out why endl can do this.