Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does bind() have any advantage (other than compatibility) over C++11 lambdas?

I'm thinking about migrating my code toward using C++11-style lambdas instead of having binds everywhere. But I'm not sure if it's a good idea or not.

Does using e.g. boost::lambda (or boost::phoenix) have any practical advantage over C++11-style lambdas?

Is it a good idea to move over to lambdas? Should I migrate my code or not?

like image 971
user541686 Avatar asked Aug 21 '12 20:08

user541686


People also ask

Are lambda functions faster c++?

sorting - Why is a C++ Lambda function much faster as compare function than an equivalent object - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

What is the advantage of lambda function in C ++?

It is a convenient way to define an anonymous function object or functor. It is convenient because we can define it locally where we want to call it or pass it to a function as an argument. Lambda is easy to read too because we can keep everything in the same place.


1 Answers

The main advantage would be polymorphic functors. Currently, C++11 lambdas are monomorphic, i.e., they only take single argument type, whereas bind() allows you to create functors that accept any argumen type as long as the bound functor is callable with it.

#include <functional>

struct X{
  template<class T, class U>
  void operator()(T, U) const{}
};

int main(){
  X x;
  auto l_with_5 = [x](int v){ return x(v, 5); };
  auto b_with_5 = std::bind(x, std::placeholders::_1, 5);
  l(4);
  b("hi"); // can't do that with C++11 lambdas
}
like image 160
Xeo Avatar answered Nov 15 '22 21:11

Xeo