Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Input basic_ostream in the template

Why don’t use ttt::focus_pocus() and is used without ()? What is the rule and why does it work here?

#include <iostream>

namespace ttt
{
  template<class CharT, class Traits>
  std::basic_ostream<CharT, Traits>& focus_pocus(std::basic_ostream<CharT, Traits> &os)
  {
    return os << "focus pocus";
  }
};

int main() 
{
  std::cout << ttt::focus_pocus << std::endl; <--- here
}

DEMO

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The << operator is overloaded to accept functions with the same signature as the focus_pocus function in your example [1]. That is the reason why you don’t call the function and don’t need () brackets.

This overload is present, to allow outputtable objects like e.g. std::endl to manipulate the output stream and for example flush it after writing a newline character. In your special case, you could just as well have written a function that returned a string.

[1]: https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading