Home > Blockchain >  Input basic_ostream in the template
Input basic_ostream in the template

Time:03-14

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

CodePudding user response:

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

  • Related