Is it possible to use C++ lambdas in the same way that Objective-C blocks are used?
Take, for example, the following Objective-C code:
@interface MyClass : NSObject
// ...
- (void)myMethodWithBlockParam:(void(^)(void))block;
//
@end
The message would be sent as follows:
[myClassInstance myMethodWithBlockParam:^{
// Do something inside block
}];
Is there a way to achieve the same effect in C++ with lambdas?
In C++ you can do
This would be called with a lambda as
This readily expands to functions with parameters and return type. Using a specialization of std::function as function parameter type allows anything that is callable with the specified signature to be passed (functions, function objects, lambdas).
Lambdas also can be closures, i.e. bind variables from their definition context by reference or by value (as a copy).