Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help me understand this usage of boost::bind

Tags:

c++

boost-bind

Please have a look at this example posted by Johannes Schaub to sort a vector of pairs:

How do I sort a vector of pairs based on the second element of the pair?

std::sort(a.begin(), a.end(), 
          boost::bind(&std::pair<int, int>::second, _1) <
          boost::bind(&std::pair<int, int>::second, _2));

I thought I do understand boost::bind, but I have trouble with this one.

Question 1:

the sort algorithm is expecting a predicate function as a third parameter. What I see here, is a boolean expression. What am I missing?:

boost::bind(&std::pair<int, int>::second, _1) < boost::bind(&std::pair<int, int>::second, _2)

Does the boost::bind library overload operator< for those two binds, and is returning some kind of function pointer (like a lambda)?

Question 2:
This gets me confused:

boost::bind(&std::pair<int, int>::second, _1)

Usually there is some kind of function pointer as first parameter of a bind call, but here it is an address of a class member? What is the result of that particular bind?

Thanks for your time & help

like image 515
nabulke Avatar asked Nov 15 '10 13:11

nabulke


2 Answers

boost::bind overloads the operator ! and the relational and logical operators ==, !=, <, <=, >, >=, &&, ||, so this is why you "see" a boolean expression, but you're really getting back a function predicate.

From there you can see that you're binding the second member of the pair for the 1st and 2nd arguments of the overloaded less than function.

As for your second question: Boost bind will recognize when you have passed a pointer to a member and treat it as if you called

bind<R>(mem_fun(&std::pair<int,int>::second), args);

This is how the documentation describes this:

Using bind with pointers to members

Pointers to member functions and pointers to data members are not function objects, because they do not support operator(). For convenience, bind accepts member pointers as its first argument, and the behavior is as if boost::mem_fn has been used to convert the member pointer into a function object. In other words, the expression

bind(&X::f, args)

is equivalent to

bind(mem_fn(&X::f), args)

where R is the return type of X::f (for member functions) or the type of the member (for data members.)

You can find this and more information here.

like image 90
RC. Avatar answered Sep 21 '22 22:09

RC.


Your theory is correct, see:

http://www.boost.org/doc/libs/1_44_0/libs/bind/bind.html#operators

like image 40
Andreas Brinck Avatar answered Sep 19 '22 22:09

Andreas Brinck