Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 223
Lukas Man Avatar asked Jul 28 '26 03:07

Lukas Man


1 Answers

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.

like image 155
101010 Avatar answered Jul 30 '26 09:07

101010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!