Reputation: 6425
Is it possible to pass lambda function with capture as a parameter of another lambda function?
int a=3;
auto func_1=[&]()->{a=4;};
auto func_2=[&]( ????? fParam ){ fParam(); }; //what is a proper ?????
func_2(func_1);
(I want to use it to do some fancy thing.)
Thank for many solutions. I have learned a lot.
In original question, I forgot to mention that func_2 also want to receive other functions e.g. func_2(func_1a), func_2(func_1b), etc.
Therefore, decltype is one of correct answers for the original question, but not fulfil my demand.
Upvotes: 2
Views: 688
Reputation: 6791
As Chris said in a comment, you could use std::function
for this. Given your concerns about auto
's inherent lack of type-checking, this has the advantage that it lets you restrict to callables of a particular signature, since std::function
is a template that is instantiated once for each signature in your program, and template instantiations aren't convertible. It can effortlessly hold a lambda, just as it can any other callable object.
This level of type-checking is probably more generally useful than the decltype(oneSpecificLambda)
version, but that's useful to know about!
Combining this with the other answers, you can thus choose to restrict your passed parameter at the point of declaration, in at least 3 ways:
auto
,std::function< T_Return(T_Args...) >
,decltype(oneSpecificLambda)
, since each lambda is a distinct unnamed type, again not convertible.Personally, I would probably just use auto
in this case and trust myself not to accidentally pass anything else. But it's good to have so many options!
Upvotes: 3
Reputation: 10770
I'm pretty sure this will work too, but as Sam Varshavchik said, if C++14 is available then just use auto.
int a=3;
auto func_1=[&]()->{a=4;};
auto func_2=[&]( decltype(func_1) fParam ){ fParam(); };
func_2(func_1);
Upvotes: 1
Reputation: 118300
That's what auto
is for:
auto func_2=[&](auto fParam ){ fParam(); };
Your compiler must have at least C++14-level language support.
EDIT: with C++11, the following appears to work:
auto func_2=[&](decltype(func_1) fParam ){ fParam(); };
Upvotes: 7