Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a 'reference' to a lambda?

Tags:

c++

c++11

lambda

I want to capture a 'reference' to a lambda, and I thought that a function pointer would do the trick, as in:

int (*factorial)(int) = [&](int x){
    return (x < 2)
        ? 1
        : x * factorial(x - 1);
};

but I get cannot convert from main::lambda<......> to int(_cdecl *)(int).

What's the proper way to point to a lambda then?

like image 996
sircodesalot Avatar asked Jun 28 '13 13:06

sircodesalot


2 Answers

Since the lambda is not stateless, it cannot be converted to a function pointer. Use std::function instead.

std::function<int(int)> factorial  = [&](int x){
  return (x < 2)
      ? 1
      : x * factorial(x - 1);
};
like image 168
Praetorian Avatar answered Sep 20 '22 21:09

Praetorian


This would be closest to what you have already:

std::function<int (int)> factorial = [&](int x){
    return (x < 2)
        ? 1
        : x * factorial(x - 1);
};

normally you could also use auto, but in this case it doesn't work because the function is recursive.

like image 23
Vaughn Cato Avatar answered Sep 19 '22 21:09

Vaughn Cato