返回一个 std::函数包装的 lambda,该 lambda 调用指向成员函数的指定指针

returning a std::function wrapped lambda that invokes a specified pointer to member function

本文关键字:函数 lambda 定指 指针 成员 调用 包装 std 一个 返回      更新时间:2023-10-16

我有一个情况,我可以将lambda传递给std::sort,我也可以通过调用一个返回一个sted::function的函数来提供谓词,该函数包装了相同的lambda,但是,如果我尝试调用一个类似的函数,该函数允许我指定指向成员函数的指针,这将编译但在运行时失败。

这有效:

std::sort(myContainer.begin(), myContainer.end(), [&](type lhs, type rhs)
{
    return MyMemberFunction(lhs, rhs);
});

这有效:

std::function<bool(type,type)> ReturnPred()
{
    std::function<bool(type,type)> pred = [&](type lhs, type rhs)
    {
        return MyMemberFunction(lhs, rhs);
    };
    return pred;
}
std::sort(myContainer.begin(), myContainer.end(), ReturnPred());

但这不起作用:

std::function<bool(type,type)> ReturnGeneralPred(
     bool(MyClass::Func*)(type lhs, type rhs))
{
    std::function<bool(type,type)> pred = [&](type lhs, type rhs)
    {
        return (this->*Func)(lhs, rhs);
    };
    return pred;
}
std::function<bool(type,type)> ReturnThisPred()
{
    return ReturnGeneralPred(&MyClass::MyMemberFunction);
}
std::sort(myContainer.begin(), myContainer.end(), ReturnThisPred());

当我尝试以最后一种通用方式执行此操作并逐步执行调试器时,当 std::sort 调用谓词时,它会步入我上面所说的 ReturnGeneralPred,并且 Func 似乎未定义,就好像它是一个超出范围的局部变量。

目前,我

可以通过失去一些通用性来获得相同的功能,但我想知道是否有一种方法可以完成我想要做的事情。

FuncReturnGeneralPred的本地,当Func超出其范围(悬空指针)时使用lambda。
通过复制捕获Func应该可以解决您的问题:

std::function<bool(type,type)> ReturnGeneralPred(bool(MyClass::Func*)(type lhs, type rhs))
{
    std::function<bool(type,type)> pred = [this, Func](type lhs, type rhs)
    {
        return (this->*Func)(lhs, rhs);
    };
    return pred;
}

或使用[=]语法而不是显式捕获[this, Func]