0

The following code fails to compile (both GCC and clang say the lambda isn't a proper function?)

#include <iostream>

using namespace std;

void apply(void f(int)) {
    f(10);
    f(20);
    f(30);
}

int main()
{
    int col = 42;

    apply([col](int data) -> void {
                  cout << data << ' ' << col << endl;
          });
}

clang++ says:

fails.cc:5:6: note: candidate function not viable: no known conversion from '(lambda at       
fails.cc:15:8)' to 'void (*)(int)' for 1st argument
void apply(void f(int)) {
     ^
1 error generated.

If you get rid of the col capture and it's use, it compiles and works fine. Rummaging in cppreference just tells me everything is OK...

What would be the point of lambdas if captures aren't allowed?

Community
  • 1
  • 1
vonbrand
  • 11,412
  • 8
  • 32
  • 52
  • 2
    A lambda is indeed not a function; it's an object of a class with overloaded `operator()`, and data members storing captured values. A capture-less lambda is convertible to a function pointer - but a lambda with captures is not (where would the captured values go?) – Igor Tandetnik Apr 26 '20 at 14:43
  • You can change `apply` to take argument of type `std::function`, this will accept capturing lambdas. – Yksisarvinen Apr 26 '20 at 14:44

1 Answers1

1

As seen here, lambdas can only be converted to function pointers if they do not capture any values. If you want to avoid this error, you can either change your lambda to not use captures, or use std::function as a parameter instead of a function pointer.

Aplet123
  • 33,825
  • 1
  • 29
  • 55