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?

8
  • possible duplicate stackoverflow.com/questions/1134388/… Commented Apr 8, 2014 at 5: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. Commented Apr 8, 2014 at 5:21
  • just call (*pManip)(std::cout) inside Commented Apr 8, 2014 at 5:22
  • Just go std::cout << pManip; Commented Apr 8, 2014 at 5:24
  • std::cout << pManip will print the address of the function. (pManip is a function pointer.) See Sveltely's answer for the proper code. Commented Apr 8, 2014 at 5:28

1 Answer 1

6
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"; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Note that a const function pointer is also permitted: e.g. void f(std::ostream&(* const pManip)(std::ostream&)).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.