Lukas Man
Lukas Man

Reputation: 115

What's the difference between lambda and std::function?

In this sample:

auto f = [](int some, int some2){
   //do something
};

This case it is a functor or object of function?

std::function<void(int, int)> f = [](int some, int some2) {
    //do something
}

Now, in this case, whats is the results? Functor or Object of function?

Upvotes: 6

Views: 2693

Answers (1)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42899

The first f (i.e., the one designated with auto) results to what is called a lambda function. Also knows as a closure. Closures are unnamed function objects. That's why we need auto to deduce the type of a closure. We don't know it's type but the compiler does. Thus, by using auto we let the compiler deduce the type of the unnamed closure object for us.

The second f (i.e., the one designated with std::function) is a std::function object. Class std::function is a general-purpose polymorphic function wrapper.

Lambdas closures as function objects can be converted to their respective std::function objects. That is exactly what is happening in:

std::function<void(int, int)> f = [](int some, int some2) {
    //do something
}

The lambda closure on the right hand side is assigned and converted to the std::function object on the left side of the assignment.

Practically, they're both interpreted as functors, since they both overload call operator() and thus can be called, except for that the lambda's type is unnamed.

Another difference between those two is that you can't assign between lambda closures, since for lambda closures the assignment operator is declared deleted. while you can assign between std::function objects.

Upvotes: 8

Related Questions