Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda as function parameter

Tags:

c++

c++11

lambda

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.

like image 840
slartibartfast Avatar asked Nov 13 '11 04:11

slartibartfast


People also ask

Can lambda functions take parameters?

A lambda function can have any number of parameters, but the function body can only contain one expression.

Which function in list takes lambda function as parameter?

You can use lambda function in filter() filter() function is used to filter a given iterable (list like object) using another function that defines the filtering logic. A lambda function is typically used to define the filtering logic and is passed as the first argument of filter() .

How do you pass a lambda function as a parameter in Java?

Passing Lambda Expressions as ArgumentsIf you pass an integer as an argument to a function, you must have an int or Integer parameter. If you are passing an instance of a class as a parameter, you must specify the class name or the object class as a parameter to hold the object.


2 Answers

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; };
like image 146
Todd Gardner Avatar answered Oct 10 '22 23:10

Todd Gardner


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 };
like image 37
David Alber Avatar answered Oct 11 '22 00:10

David Alber