布尔函数作为输入参数

cls*_*udt 3 c++ lambda signature c++11

我想写一个方法,它执行一些操作,直到终止标准变为真.该终止标准应由用户给出,并且可以是任何标准.

我正在考虑将一个带有返回类型boolean(可能是一个闭包)的函数传递给该方法,并将其作为while循环的条件调用.

在Python中,这将是

class Example:

    def doSomething(self, amIDone):
        while not amIDone():
            something()
        return
Run Code Online (Sandbox Code Playgroud)

我怎样才能在C++ 11中表达这一点?

And*_*owl 8

您可以使您的函数成为模板,并让它接受任何返回的可调用对象bool.例如:

template<typename P>
void doSomething(P&& p)
{
    while (p())
    {
        something();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是你通过传递lambda来调用它的方法,例如:

int main()
{
    // Possibly pass a more clever lambda here...
    doSomething([] () { return true; });
}
Run Code Online (Sandbox Code Playgroud)

当然你可以传递一个普通的仿函数而不是一个lambda:

struct my_functor
{
    // Possibly write a more clever call operator here...
    bool operator () ()
    {
        return true;
    }
};

int main()
{
    doSomething(my_functor());
}
Run Code Online (Sandbox Code Playgroud)

函数指针也是一个选项:

// Possibly use a more clever function than this one...
bool my_predicate()
{
    return true;
}

int main()
{
    doSomething(my_predicate);
}
Run Code Online (Sandbox Code Playgroud)

如果你有理由不使你的函数成为模板(例如,因为它是virtual某个类的成员函数),你可以使用std::function:

void doSomething(std::function<bool()> p)
{
    while (p())
    {
        something();
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的所有示例都可以很好地工作std::function,但这肯定会花费您一些运行时开销(尽管这可能与您的用例无关).