C++11 Change `auto` Lambda to a different Lambda?

A Lambda may be converted to a function pointer using the unary + operator like so:

+[]{return true;}

so long as the capture group is empty and it doesn’t have auto arguments.1

If you do this, you may assign different lambdas to the same variable as long as the lambdas all have the same signature.

In your case,

auto a = +[]{return true;};
a = +[]{return false;};

Live example on Coliru

would both compile and act as you expect.2 You may use the function pointers in the same way you would expect to use a lambda, since both will act as functors.


1. In C++14, you can declare lambdas with auto as the argument type, like [](auto t){}. These are generic lambdas, and have a templated operator(). Since a function pointer can’t represent a templated function, the + trick won’t work with generic lambdas.

2. Technically, you don’t need the second + operator on the assignment. The lambda would convert to the function pointer type on assignment. I like the consistency, though.

Leave a Comment