Can I define a C ++ lambda function without auto?

I have a lot of C # experience, but I'm new to C ++. I saw this problem when trying to use lambda as I did.

For instance:

auto compare = [] (int i1, int i2) { return i1*2 > i2; } 

Is there a way to detect a lambda of a particular type, rather than automatic output?

I ask about this because I want to define a common lambda for my class. This lambada will be used in several places, so I do not want to define them several times. However, "auto" can only be used for static members, and on the other hand, I want to access non-static fields in lambda.

+6
source share
3 answers

You are using the std :: function. std :: function can glob any Lambda or Function pointer. http://en.cppreference.com/w/cpp/utility/functional/function

std::function< bool(int, int) > myFunc = []( int x, int y ){ return x > y; };

+7
source

You can use std::function , but if that is not efficient enough, you can write a functor object similar to what lambdas do behind the scenes:

 auto compare = [] (int i1, int i2) { return i1*2 > i2; } 

almost coincides with

 struct Functor { bool operator()(int i1, int i2) const { return i1*2 > i2; } }; Functor compare; 

If a functor needs to grab some variable in a context (for example, 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); } 

almost coincides with

 struct Functor { Object *that; Functor(Object *that) : that(that) {} void operator()(int i) const { return that->bar(i); } }; Functor foo(this); 
+3
source

You can use as std::function<Signature> , as mentioned, but by erasing the lambda. When calling your lambda, this will add indirection (basically calling a virtual function). Therefore, keep in mind that it is less effective if you use it in a context where it matters.

0
source

Source: https://habr.com/ru/post/977165/


All Articles