问题
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?
回答1:
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";
}
来源:https://stackoverflow.com/questions/22927906/how-pass-stdendl-to-a-function-and-use-it