【问题标题】:How to assign a new lambda expression to a function object? [duplicate]如何将新的 lambda 表达式分配给函数对象? [复制]
【发布时间】: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_2 type 是用于初始化它的 lambda 的类型...这 2 个 lambda 有 2 种不同的类型。
  • 您可以使用using MyFunc_t = function&lt;bool(const my_pair &amp;,const my_pair &amp;)&gt;;typedef 来获得更短的名称并使用它来代替auto comp_2 = ... - MyFunc_t comp_2 = ...
  • 可以传递不同的实现through a lambda to unify the types。但是我不建议这样做——考虑到您调用将 lambda 传递给通用 lambda 的可变参数 lambda 结果,错误质量会显着降低。

标签: c++ c++11 lambda constants


【解决方案1】:

每个 lambda 表达式都是匿名类型的文字;两个不同的 lambda,即使是相同的原型和相同的捕获列表,也是两种不同类型的对象。而且,this type's assignment operator is deleted,所以你甚至不可能将它分配给它自己:

$ 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 2022-01-23
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多