Question

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?

Was it helpful?

Solution

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"; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top