Lambda as function parameter

C++LambdaC++11

C++ Problem Overview


What's the notation for declaring a lambda variable, or function parameter, without the use of auto or templates? Is there any way to do so? Or does the compiler define a unique class object for each lambda whose name is unknown to the programmer before compile time? If so, why? Can't they just be passed as some sort of function pointer? It would be a major disappointment if that were not possible.

C++ Solutions


Solution 1 - C++

Lambdas may hold state (like captured references from the surrounding context); if they don't, they can be stored in a function pointer. If they do, they have to be stored as a function object (because there is no where to keep state in a function pointer).

// No state, can be a function pointer:
int (*func_pointer) (int) = [](int a) { return a; };

// One with state:
int b = 3;
std::function<int (int)> func_obj = [&](int a) { return a*b; };

Solution 2 - C++

You can use a polymorphic wrapper for a function object. For example:

#include <functional>

std::function<double (double, double)> f = [](double a, double b) { return a*b };

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionslartibartfastView Question on Stackoverflow
Solution 1 - C++Todd GardnerView Answer on Stackoverflow
Solution 2 - C++David AlberView Answer on Stackoverflow