Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep parameters in binds

Tags:

c++

c++11

bind

I wrote the following code without thinking much about what I was doing and I'm really surprised that it actually works as I intended.

Could someone explain why and how bind manages to work with deep parameters?

#include <string>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
using namespace placeholders;

int main()
{
    vector<string> s = { "abc", "aaaaaaa", "c" };

    for_each(s.begin(),s.end(),
             bind(printf,"string length is %d\n",bind(&string::length,_1)));
}
like image 805
Šimon Tóth Avatar asked Aug 22 '26 06:08

Šimon Tóth


1 Answers

The standard defines the unary type trait is_bind_expression<T> which is true if T is a call wrapper type returned from std::bind(), or if the trait has been specialized for user-defined types.

When the call wrapper is invoked, if any of its bound arguments is a bind expression (as determined by is_bind_expression) then that nested bind expression is invoked with all the same arguments as the outer expression was invoked with. The nested bind expression can select out any arguments for which it has a placeholder (_1 in your example). This is done recursively, so that invoking the inner bind expression will also check if any of its bound arguments is a bind expression, and invoke them with the same set of arguments and so on.

like image 116
Jonathan Wakely Avatar answered Aug 24 '26 20:08

Jonathan Wakely



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!