P45 Imminent
P45 Imminent

Reputation: 8591

What is the type of a lambda?

I've seen code like this:

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

Obviously the 3rd parameter of std::sort is a type that can hold the lambda. But what is that type? std::sort is so heavily overloaded I can't decipher it.

(I'm thinking of building up a list of functions: am thinking of using lambdas rather than function pointers as the latter have to have broadly the same parameter list).

I guess I could write

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

but that won't help me when it comes to using a container.

Upvotes: 5

Views: 513

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361322

The type of lambda is unique, known to the compiler. In your code, std::sort is a function template, whose third parameter is a template parameter which is deduced by the compiler, for the lambda you pass to the function.

Usually you don't need to know the type of the lambda as it is defined by the compiler for you, something like below:

//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); 
       }
};

So your code translates to this:

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

Note that if you want to have a container of lambda (and function pointers!), then you could use std::function to erase the type of the lambda (and function pointers), something like this:

 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!

Upvotes: 7

Related Questions