Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a lambda as a parameter for a C++ function

I would like to use a lambda as a parameter for a C++ function, but I don't know which type to specify in the function declaration. What I would like to do is this:

void myFunction(WhatToPutHere lambda){     //some things } 

I have tried void myFunction(auto lambda) and void myFunction(void lambda) but none of these codes compiled. In case it matters, the lambda doesn't return anything.

How can I use a lambda as a parameter in a C++ function?

like image 633
Donald Duck Avatar asked Nov 28 '16 12:11

Donald Duck


People also ask

Is there lambda function in C?

Significance of Lambda Function in C/C++ Lambda Function − Lambda are functions is an inline function that doesn't require any implementation outside the scope of the main program. Lambda Functions can also be used as a value by the variable to store.

Is lambda a parameter?

A Python lambda function behaves like a normal function in regard to arguments. Therefore, a lambda parameter can be initialized with a default value: the parameter n takes the outer n as a default value. The Python lambda function could have been written as lambda x=n: print(x) and have the same result.

How do you call a lambda in C++?

A lambda is also just a function object, so you need to have a () to call it, there is no way around it (except of course some function that invokes the lambda like std::invoke ). If you want you can drop the () after the capture list, because your lambda doesn't take any parameters.


2 Answers

You have 2 ways: make your function template:

template <typename F> void myFunction(F&& lambda) {     //some things } 

or erase type (with std::function for example):

void myFunction(const std::function<void()/*type of your lamdba::operator()*/>& f) {     //some things } 
like image 102
Jarod42 Avatar answered Oct 06 '22 11:10

Jarod42


You have two choices, basically.

Make it a template:

template<typename T> void myFunction(T&& lambda){ } 

or, if you do not want (or can't) do that, you can use type-erased std::function:

void myFunction(std::function<void()> const& lambda){ } 

Conversely, your attempt with auto would've been correct under the concepts TS as currently implemented in gcc, where it'd be an abbreviated template.

// hypothetical C++2x code void myFunction(auto&& lambda){ } 

or with a concept:

// hypothetical C++2x code void myFunction(Callable&& lambda){ } 
like image 34
krzaq Avatar answered Oct 06 '22 11:10

krzaq