【发布时间】:2018-01-22 14:33:51
【问题描述】:
已定义 lambda 表达式并将其分配/绑定到函数对象。现在我想为该函数对象分配一个新函数。但是这个赋值在某些情况下会导致编译错误。
我了解错误来自auto 关键字自动将const 添加到函数对象。无论如何使用auto 和其他关键字来删除const 绑定?我真的不相信 mutable 可以达到我的代码中的目的。
This 帖子解释了为什么没有解决方案。 This post 提出了使用结构体的解决方案,但我想知道是否有更优雅的方式来做到这一点。
#include <functional>
#include <memory>
#include <queue>
#include <random>
#include <utility>
using namespace std;
void f1();
int main() {
srand(0);
f1();
return 0;
}
void f1() {
using my_pair = pair<int,int>;
int ref = 2;
function<bool(const my_pair &,const my_pair &)> comp_1 = [&ref](const my_pair &LHS, const my_pair &RHS) {return LHS.first-ref > RHS.first-ref;};
comp_1 = [&ref](const my_pair &LHS, const my_pair &RHS) {return LHS.first < RHS.first;};
// So far so good.
auto comp_2 = [&ref](const my_pair &LHS, const my_pair &RHS) mutable {return LHS.first-ref > RHS.first-ref;};
// Compile error below!
comp_2 = [&ref](const my_pair &LHS, const my_pair &RHS) mutable {return LHS.first < RHS.first;};
// Compile error above
// Applications of the function object
priority_queue<my_pair, vector<my_pair>, decltype(comp_2)> myHeap(comp_2);
for (int i=0; i<10; i++) myHeap.emplace(rand()%10,rand()%20);
while (!myHeap.empty()) {
printf("<%d,%d>\n",myHeap.top().first,myHeap.top().second);
myHeap.pop();
}
}
【问题讨论】:
-
准确的错误信息会很有用。
-
“我了解到错误来自auto关键字自动添加const”什么?这里的问题是
auto被推导出为lambda类型,而不是std::function,并且每个lambda都有自己的类型,所以你不能为前一个分配一个新的lambda。 -
comp_2type 是用于初始化它的 lambda 的类型...这 2 个 lambda 有 2 种不同的类型。 -
您可以使用
using MyFunc_t = function<bool(const my_pair &,const my_pair &)>;或typedef来获得更短的名称并使用它来代替auto comp_2 = ...-MyFunc_t comp_2 = ...。 -
你可以传递不同的实现through a lambda to unify the types。但是我不建议这样做——考虑到您调用将 lambda 传递给通用 lambda 的可变参数 lambda 结果,错误质量会显着降低。
标签: c++ c++11 lambda constants