[英]Boolean function as input parameter
I want to write a method which performs some action until a termination criterion becomes true. 我想写一个方法,它执行一些操作,直到终止标准变为真。 This termination criterion should be given by the user, and it can be any criterion.
该终止标准应由用户给出,并且可以是任何标准。
I was thinking about passing a function with return type boolean (possibly a closure) to the method and call it as the condition of a while loop. 我正在考虑将一个带有返回类型boolean(可能是一个闭包)的函数传递给该方法,并将其作为while循环的条件调用。
In Python, this would be 在Python中,这将是
class Example:
def doSomething(self, amIDone):
while not amIDone():
something()
return
How can I express this in C++11? 我怎样才能在C ++ 11中表达这一点?
You could make your function a template and let it accept any callable object that returns a bool
. 您可以使您的函数成为模板,并让它接受任何返回
bool
可调用对象。 For instance: 例如:
template<typename P>
void doSomething(P&& p)
{
while (p())
{
something();
}
}
This is how you could invoke it by passing a lambda, for instance: 这是你通过传递lambda来调用它的方法,例如:
int main()
{
// Possibly pass a more clever lambda here...
doSomething([] () { return true; });
}
Of course you could pass a regular functor instead of a lambda: 当然你可以传递一个普通的仿函数而不是一个lambda:
struct my_functor
{
// Possibly write a more clever call operator here...
bool operator () ()
{
return true;
}
};
int main()
{
doSomething(my_functor());
}
A function pointer is also an option: 函数指针也是一个选项:
// Possibly use a more clever function than this one...
bool my_predicate()
{
return true;
}
int main()
{
doSomething(my_predicate);
}
If you have reasons for not making your function a template (for instance, because it is a virtual
member function of some class), you could use std::function
: 如果你有理由不让你的函数成为模板(例如,因为它是某个类的
virtual
函数成员函数),你可以使用std::function
:
void doSomething(std::function<bool()> p)
{
while (p())
{
something();
}
}
All the examples above will work equally well with std::function
, but this will certainly cost you some run-time overhead (which may be irrelevant for your use cases, though). 上面的所有示例都可以与
std::function
一样好用,但这肯定会花费你一些运行时开销 (尽管这可能与你的用例无关)。
you could do this using std::function
from the <functional>
headers. 你可以使用
<functional>
头文件中的std::function
来做到这一点。
The predicate is looking like this: 谓词看起来像这样:
bool predicate()
{
...
return false;
}
And this is your class using the predicate functor 这是使用谓词仿函数的类
struct A
{
void test (std::function<bool(void)> func)
{
while( func() )
{
perform();
}
}
}
and you can call it this way: 你可以这样称呼它:
A a;
a.test(predicate);
In this example I took the function bool predicate()
as a predicate. 在这个例子中,我将函数
bool predicate()
作为谓词。 But a lambda function or a class defining bool operator()
would have worked the same. 但是lambda函数或定义
bool operator()
的类可以使用相同的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.