如何将新的 lambda 表达式分配给函数对象?
How to assign a new lambda expression to a function object?
已定义 lambda 表达式并将其分配/绑定到函数对象。现在我想为该函数对象分配一个新函数。但是在某些情况下,此分配会导致编译错误。
我知道错误来自auto
关键字自动将const
添加到函数对象。有没有办法将auto
与其他关键字一起使用来删除const
绑定?我真的不相信mutable
可以像我的代码那样达到目的。
这篇文章解释了为什么没有解决方案。 这篇文章提出了一个使用结构的解决方案,但我想知道是否有更优雅的方法。
#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();
}
}
每个 lambda 表达式都是匿名类型的文本;两个不同的 lambda,即使是相同的原型和相同的捕获列表,也是两种不同类型的对象。此外,此类型的赋值运算符被删除,因此您甚至无法将其分配给自身:
$ cat omg.cpp
int main() {
auto f = []{};
f = f;
}
$ g++ omg.cpp
omg.cpp: In function ‘int main()’:
omg.cpp:3:4: error: use of deleted function ‘main()::<lambda()>& main()::<lambda()>::operator=(const main()::<lambda()>&)’
f = f;
^
omg.cpp:2:12: note: a lambda closure type has a deleted copy assignment operator
相关文章:
- 无法分配函数指针的 2D 数组
- Clang-Format 不能正确分配函数参数
- 我们可以在cpp中为对象分配函数吗
- 分段错误分配函数结果
- 在类内分配函数指针
- 创建一个移动分配函数,不断得到"pointer being freed was not allocated"
- 如何在C++中重新分配函数名称
- 尝试分配函数指针时获取"Void value not ignored as it ought to be"
- 尝试从文件中获取数据时,在C 中的分配函数中没有正确的字符串
- 当使用内存分配函数用作条件语句时会发生什么
- 解除分配函数的 A 函数 B 内的运行时内存
- 是否可以编写一个自定义 STL 分配器,该分配器使用指向用户提供的分配函数的指针
- 当分配函数指针时,这两种符号之间有什么区别
- 新的运算符分配函数顺序连续性和初始值
- 在类中分配函数指针会在C++中给出值类型错误
- 函数包装中的堆栈分配/函数中的alloca
- 创建线程,在循环中为其分配函数并执行
- 我想我可以理解 N5.3.4 中的 §4140/11,但已扩展的分配函数的概念对我来说是不可理解的
- 析构函数和解分配函数的区别是什么?
- 为什么分配函数使用std::nothrow_t作为引用而不是值