简体   繁体   English

将 lambda 表达式传递给模板调用函数时没有匹配的函数编译错误?

[英]No matching function compile error when passing lambda expression to a templated caller function?

Code:代码:

#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;
}

If I compile this with clang++ -std=c++11 mutable_lambda.cpp , I got error: no matching function for call to object of type 'const (lambda at mutable_lambda.cpp:8:22)' .如果我用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)'

Question: Why passing the second lambda expression with mutable copy capture failed to compile?问题:为什么传递带有可变副本捕获的第二个 lambda 表达式编译失败? Thanks in advance!提前致谢!

A mutable lambda has a non- const operator() . mutable lambda 具有非const operator() You are trying to call this non- const operator() through a const reference.您正在尝试通过const引用调用此非const operator() That doesn't work for the same reason that calling any non- const non-static member function doesn't work through a const reference.这不起作用的原因与调用任何非const非静态成员函数不能通过const引用工作的原因相同。


If you want to allow caller to modify the passed function object (through a non- const operator() call) if it is passed as non- const argument, then take it by forwarding reference instead of const reference:如果要允许caller修改传递的函数对象(通过非const operator()调用),如果它作为非const参数传递,则通过转发引用而不是const引用来获取它:

template <class FunctorType>
void caller(FunctorType&& func) {
  func(); // maybe std::forward<FunctorType>(func)();
}

Also note that change_data does not change the data in main .另请注意, change_data不会更改main中的data It changes a copy of it stored inside the lambda.它更改了存储在 lambda 中的副本。 If you want it to change the data in main , you need to capture data by-reference and then the lambda itself also doesn't need to be mutable anymore:如果您希望它更改main中的data ,则需要通过引用捕获data ,然后 lambda 本身也不再需要是mutable的:

auto change_data = [&data]() { data[0] = 4.2; };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM