返回一个 std::函数包装的 lambda,该 lambda 调用指向成员函数的指定指针
returning a std::function wrapped lambda that invokes a specified pointer to member function
我有一个情况,我可以将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 似乎未定义,就好像它是一个超出范围的局部变量。
目前,我可以通过失去一些通用性来获得相同的功能,但我想知道是否有一种方法可以完成我想要做的事情。
Func
是ReturnGeneralPred
的本地,当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]
。
相关文章:
- 可组合的lambda/std::函数与std::可选
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 如何将lambda作为模板类的成员函数参数
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 模板函数指针和lambda
- 两组使用lambda函数的大括号
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 在构造函数中使用 lambda 的 C++ 类
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- 为什么我不能在 constexpr lambda 函数中使用 std::tuple
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- C++:Lambda 函数指针转换的用例是什么?
- 将有状态的 lambda 传递到 C 样式函数中,而无需上下文参数
- std::映射服装比较函数和函数/lambda错误
- 在可移动类型的构造函数 lambda 中捕获此内容的安全使用
- 排序测试模板化函数 lambda:非法使用此类型作为表达式
- 将匿名函数(lambda)保存为函数类型变量
- 如何编写将自身作为回调传递的匿名函数/lambda