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

≯℡__Kan透↙ 提交于 2019-12-11 08:38:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!