3

Given the following typedef function pointer:

typedef void(*vfp)();

We can certainly point to a void function as follows:

string s = "Gordon Freeman: Lambdas have no half-lives.";

void f() {
    cout << s;
}

int main(int argc, char **argv)
{
    vfp p;
    p = f;
    p();
}

But how can I point to a lambda expression?

typedef void(*vfp)();

int main(int argc, char **argv)
{
    string s = "Gordon Freeman: Lambdas have no half-lives.";
    vfp p;
    p = [&s]()->void{cout<<s;}; // Error, lambdas do not return "function objects" as in Python.
    p();
}

Error:

cannot convert 'main(int, char**)::__lambda0' to 'vfp {aka void (*)()}' in assignment.

So, if I can't point to an anonymous lambda function in the same way I can point to a function, they are not functions (And they should be. If they're not, why they're not?)

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114
  • 5
    Lambdas aren't functions, the standard defines them in terms of functors. A lambda with no captures can be implicitly converted to a function pointer, that still doesn't make it a function. If you want to store a capturing lambda you need to use `auto` or `std::function`. – user657267 Jun 15 '15 at 22:39

0 Answers0