0

I was doing a quick experiment with lambda functions and I'm having trouble figuring out how to declare the testFunc variable below.

Generally speaking, a function pointer can be defined as follows:

int (*someFunc)(int, int) = otherFunction;

When doing this for a lambda function without any closures, it works fine:

int (*someFunc)(int) = [](int a) -> int { return 0; };

However, I get a compiler error when trying to capture by reference:

void (*testFunc)() = [&]() -> void { /* code here */ };

It works if I declare testfunc as auto instead, but I'm curious what's wrong with the above code?

Gogeta70
  • 881
  • 1
  • 9
  • 23
  • 1
    you can use `std::function` but should be aware of overhead, it is pretty small but exists. – Slava Jan 09 '18 at 22:36

1 Answers1

2

It's pretty simple:

All lambdas have unique anonymous types. (that's why auto works)

Lambdas without captures are convertible to function pointers, but capturing lambdas are not.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207