What type of lambda?

I saw a code like this:

std::sort(x, x + N, 
    // Lambda expression begins
    [](float a, float b) { 
        return std::abs(a) < std::abs(b); 
    });

Obviously, the third parameter std::sortis the type that lambda can contain. But what type is this? std::sortso overloaded that I can’t decrypt it.

(I'm going to create a list of functions: I'm thinking about using lambdas, not function pointers, since the latter should have the same parameter list as a whole).

I think I could write

auto letTheComplerSortOutTheType =
        [](float a, float b) { 
            return std::abs(a) < std::abs(b); 
        });

but that will not help me when it comes to using a container.

+4
source share
1 answer

, . std::sort - , , , .

, , - :

//generated by the compiler
struct __unique_lambda_defined_by_compiler  //arbitrary ugly name!
{
       bool operator()(float a, float b) const { 
                return std::abs(a) < std::abs(b); 
       }
};

, :

//translated by the compiler
std::sort(x, x + N, __unique_lambda_defined_by_compiler());

, ( !), std::function ( ), :

 std::vector<std::function<bool(int,int)>> callbacks;

 callbacks.push_back([](int, int) { ... });  //the lambda must return bool
 callbacks.push_back([](int, int) { ... });
 callbacks.push_back([](int, int) { ... });

 bool compare(int,int) { ... } 

 callbacks.push_back(compare); //store normal function as well!
+6

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


All Articles