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?
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.
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.
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.
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 }
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){ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With