如何将std :: endl传递给函数并使用它? [英] How pass std::endl to a function and use it?
本文介绍了如何将std :: endl传递给函数并使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想弄清楚如何将像std::endl
这样的操纵器传递给函数,然后在函数中使用传入的操纵器.我可以这样声明函数:
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&));
我可以这样称呼它:
f(std::endl);
没关系.我的问题是弄清楚如何在f
中使用操纵器.这不起作用:
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
}
无论编译器如何,错误消息都归结为编译器无法确定要调用哪个operator<<
.我需要在f
内部进行哪些修复才能编译我的代码?
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?
推荐答案
void f(std::ostream&(*pManip)(std::ostream&))
{
std::cout << "before endl" << (*pManip) << "after endl";
}
或
void f(std::ostream&(*pManip)(std::ostream&))
{
std::cout << "before endl";
(*pManip)(std::cout);
std::cout << "after endl";
}
这篇关于如何将std :: endl传递给函数并使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文