Search code examples
c++boostbind

The purpose of Function Binding


I am learning asio programming of c++ Boost library. And I have encountered many examples that use the function bind() which has function pointer as argument.

I have not been able to understand the use of bind() function. And that's why I have difficulty in understanding programs using asio of boost library.

I am not seeking for any code here. I just want to know the use of bind() function or any of its equivalent function. Thanks in advance.


Solution

  • From cppreference

    The function template bind generates a forwarding call wrapper for f. Calling this wrapper is equivalent to invoking f with some of its arguments bound to args.

    Check the example below demonstrating bind

    #include <iostream>
    #include <functional>
    
     using namespace std;
    
    int my_f(int a, int b)
    {
        return 2 * a + b;
    }
    
    int main()
    {
        using namespace std::placeholders;  // for _1, _2, _3...
    
         // Invert the order of arguments
         auto my_f_inv = bind(my_f, _2, _1);        // 2 args b and a
        // Fix first argument as 10
        auto my_f_1_10 = bind(my_f, 10, _1);        // 1 arg b
        // Fix second argument as 10
        auto my_f_2_10 = bind(my_f, _1, 10);        // 1 arg a
        // Fix both arguments as 10
        auto my_f_both_10 = bind(my_f, 10, 10);     // no args
    
        cout << my_f(5, 15) << endl; // expect 25
        cout << my_f_inv(5, 15) << endl; // expect 35
        cout << my_f_1_10(5) << endl; // expect 25
        cout << my_f_2_10(5) << endl; // expect 20
        cout << my_f_both_10() << endl; // expect 30
    
        return 0;
    }
    

    You can use bind to manipulate an existing function's argument order or fix some arguments. This can be particularly helpful in stl container and algorithms where you can pass an existing library function whose signature matches with your requirement.

    For example if you want to transform all your doubles in your container to power 2, you can simply do something like:

    std::transform(begin(dbl_vec),
                   end(dbl_vec),
                   begin(dbl_vec),
                   std::bind(std::pow, _1, 2));
    

    Live example here