Can boost::lambda be used recursively?
This doesn't compile:
using namespace boost::lambda;
auto factorial = (_1 == 0) ? 1 : factorial(_1-1);
Is there a suggested workaround?
EDIT: Regarding using C++11 lambdas: The following does not compile on VS2012:
std::function<int(int)> factorial;
factorial = [&factorial](int p)->int { return (p == 0) ? 1 : p*factorial(p-1); };
int main(int argc, char* argv[])
{
int i = factorial(5);
return 0;
}
ANOTHER EDIT: Strangely, this one works fine:
std::function<int(int)> factorial =
[&](int p)->int { return (p == 0) ? 1 : p*factorial(p-1); };
int main(int argc, char* argv[])
{
int i = factorial(5);
return 0;
}
The simplest way I've found with regular C++11 lambdas is to declare the variable that will contain the lambda first, then define it and create the lambda. Already being declared allows for the declaration to be used in the definition/lambda itself. Eg:
So far I haven't had any problems with that method, although you do have to know the signature for the declaration and I don't know whether it works with boost::lambda (I would assume so?).