I have plenty of C# experience before but I am new to C++. I have seen this problem when trying to use lambda as I used to do.
For example:
auto compare = [] (int i1, int i2) { return i1*2 > i2; }
Is there any way to define the lambda with a specific type, rather than auto deduction?
I am asking this because I want to define a common lambda for my class. This lambada will be used in multiple places so I don't want to define them multiple times. However, 'auto' can only be used on static members, while on the other hand, I want to access non-static fields in the lambda.
You give the function a value (argument) and then provide the operation (expression). The keyword lambda must come first. A full colon (:) separates the argument and the expression. In the example code below, x is the argument and x+x is the expression.
We propose the inclusion of simple lambda expressions into the C standard. We build on a slightly restricted syntax of that feature in C++. In particular, they only have immutable value captures, fully specified pa- rameter types, and, based on N2891, the return type is inferred from return statements.
A lambda expression is an anonymous function that provides a concise and functional syntax, which is used to write anonymous methods. It is based on the function programming concept and used to create delegates or expression tree types. The syntax is function(arg1, arg2... argn) expression.
Creating a Lambda Expression in C++auto greet = []() { // lambda function body }; Here, [] is called the lambda introducer which denotes the start of the lambda expression. () is called the parameter list which is similar to the () operator of a normal function.
You use std::function
, which can glob any lambda or function pointer.
std::function< bool(int, int) > myFunc = []( int x, int y ){ return x > y; };
See C++ Reference.
You could use std::function
, but if that's not going to be efficient enough, you could write a functor object which resembles what lambdas do behind the scenes:
auto compare = [] (int i1, int i2) { return i1*2 > i2; }
is almost the same as
struct Functor {
bool operator()(int i1, int i2) const { return i1*2 > i2; }
};
Functor compare;
If the functor should capture some variable in the context (e.g. the "this" pointer), you need to add members inside the functor and initialize them in the constructor:
auto foo = [this] (int i) { return this->bar(i); }
is almost the same as
struct Functor {
Object *that;
Functor(Object *that) : that(that) {}
void operator()(int i) const { return that->bar(i); }
};
Functor foo(this);
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