gpt4 book ai didi

c++ - 返回调用指向成员函数的指定指针的 std::function 包装的 lambda

转载 作者:行者123 更新时间:2023-11-28 07:11:56 24 4
gpt4 key购买 nike

我有一个例子,我可以将一个 lambda 传递给 std::sort,我也可以通过调用一个函数来提供谓词,该函数返回一个 std::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]

关于c++ - 返回调用指向成员函数的指定指针的 std::function 包装的 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20837807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com