How pass std::endl to a function and use it?
Asked Answered
E

1

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?

Egocentrism answered 8/4, 2014 at 5:0 Comment(8)
possible duplicate #1134888Fons
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.Egocentrism
just call (*pManip)(std::cout) insideFons
Just go std::cout << pManip;Lentissimo
std::cout << pManip will print the address of the function. (pManip is a function pointer.) See Sveltely's answer for the proper code.Egocentrism
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)Fons
My mistake, you're right. Thanks for the education.Egocentrism
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 attentiveFons
B
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"; 
}
Bryannabryansk answered 8/4, 2014 at 5:23 Comment(1)
Note that a const function pointer is also permitted: e.g. void f(std::ostream&(* const pManip)(std::ostream&)).Carburet

© 2022 - 2024 — McMap. All rights reserved.