Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of a function is endl? How do I define something like endl? [duplicate]

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.

like image 583
oldink Avatar asked Oct 19 '16 04:10

oldink


2 Answers

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.

like image 72
krzaq Avatar answered Nov 14 '22 22:11

krzaq


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 << "  : ?");
}
like image 37
R Sahu Avatar answered Nov 14 '22 22:11

R Sahu