【问题标题】:No matching function compile error when passing lambda expression to a templated caller function?将 lambda 表达式传递给模板调用函数时没有匹配的函数编译错误?
【发布时间】:2022-07-23 01:16:50
【问题描述】:

代码:

#include <iostream>

template <class FunctorType>
void caller(const FunctorType& func) {
  func();
}

int main() {
  double data[5] = {5., 0., 0., 0., 0.};
  auto peek_data = [data]() { std::cout << data[0] << std::endl; };
  auto change_data = [data]() mutable { data[0] = 4.2; };

  caller(peek_data);    // This works
  caller(change_data);  // This doesn't
  return 0;
}

如果我用clang++ -std=c++11 mutable_lambda.cpp 编译它,我得到了 error: no matching function for call to object of type 'const (lambda at mutable_lambda.cpp:8:22)'.

问题: 为什么传递第二个 lambda 表达式可变复制捕获编译失败?提前致谢!

【问题讨论】:

  • 如果你记得 lambda 只是一个匿名类的实例,它有一个 () 运算符,默认是一个 const 和一个可变的一个是非-const 一个。现在看看你的模板参数声明为什么,看看这个史酷比之谜现在是否可以解决。

标签: c++ templates lambda capture


【解决方案1】:

mutable lambda 有一个非const operator()。您正在尝试通过 const 引用将此非 const operator() 称为。这不起作用的原因与调用任何非const 非静态成员函数不能通过const 引用起作用的原因相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 2021-06-28
    • 2019-05-26
    • 2021-02-25
    • 2017-03-07
    • 1970-01-01
    相关资源
    最近更新 更多