1

I want to figure out how to pass a manipulator like std::endl to a function and then use the passed-in manipulator in the function. I can declare the function like this:

void f(std::ostream&(*pManip)(std::ostream&));

and I can call it like this:

f(std::endl);

That's all fine. My problem is figuring out how to use the manipulator inside f. This doesn't work:

void f(std::ostream&(*pManip)(std::ostream&))
{
  std::cout << (*pManip)(std::cout);            // error
}

Regardless of compiler, the error message boils down to the compiler not being able to figure out which operator<< to call. What do I need to fix inside f to get my code to compile?

KnowItAllWannabe
  • 12,972
  • 8
  • 50
  • 91
  • possible duplicate http://stackoverflow.com/questions/1134388/stdendl-is-of-unknown-type-when-overloading-operator – qwr Apr 08 '14 at 05:14
  • I don't think it's the same question. I don't want to create a custom manipulator, I just want to use an existing manipulator that's passed as an argument to a function. – KnowItAllWannabe Apr 08 '14 at 05:21
  • just call (*pManip)(std::cout) inside – qwr Apr 08 '14 at 05:22
  • Just go `std::cout << pManip;` – M.M Apr 08 '14 at 05:24
  • `std::cout << pManip` will print the address of the function. (`pManip` is a function pointer.) See Sveltely's answer for the proper code. – KnowItAllWannabe Apr 08 '14 at 05:28
  • function pointers can be used this way too.So std::cout << pManip; should be ok. Indeed on your own code the problem was that you were passing result of (*pManip)(std::cout) to <<(stream output function) – qwr Apr 08 '14 at 05:36
  • My mistake, you're right. Thanks for the education. – KnowItAllWannabe Apr 08 '14 at 05:44
  • We all do such errs.It is cause of not being attentive. Being not attentive can lead such minor errors.Plus with c++ one should be a bit more attentive – qwr Apr 08 '14 at 05:52

1 Answers1

5
void f(std::ostream&(*pManip)(std::ostream&))
{
  std::cout << "before endl" << (*pManip) << "after endl"; 
}

or

void f(std::ostream&(*pManip)(std::ostream&))
{
  std::cout << "before endl";
  (*pManip)(std::cout);
  std::cout << "after endl"; 
}
Sveltely
  • 822
  • 1
  • 8
  • 22
  • Note that a `const` function pointer is also permitted: e.g. `void f(std::ostream&(* const pManip)(std::ostream&))`. – user2023370 May 07 '20 at 11:31