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.
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.
std::ostream
has a member function overload
std::ostream& operator<<(std::ostream& (*func)(std::ostream&));
That means you can use
std::cout << ain;
if ain
is declared as:
std::ostream& ain(std::ostream& out);
Its implementation would be something like:
std::ostream& ain(std::ostream& out)
{
return (out << " : ?");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With