Tuesday, August 22, 2017

C++11: bind

The template std::bind was added. It allows you to created a function wrapper that binds some of the arguments.

#include <functional>
#include <iostream>

int add(int lhs, int mhs, int rhs) {return lhs + mhs + rhs;}

int main()
{
  auto f_add_0 = std::bind(
                        add                  ,
                        std::placeholders::_1,
                        std::placeholders::_2,
                        std::placeholders::_3);

  auto f_add_1 = std::bind(
                        add                  ,
                        std::placeholders::_1,
                        std::placeholders::_2,
                        10                   );

  auto f_add_2 = std::bind(
                        add                  ,
                        std::placeholders::_1,
                        10                   ,
                        100                  );

  auto f_add_3 = std::bind(
                        add                  ,
                        1                    ,
                        10                   ,
                        100                  );
  
  std::cout << f_add_0(1, 2, 3) << " " <<
               f_add_1(1, 2   ) << " " <<
               f_add_2(9      ) << " " <<
               f_add_3(       ) << " " << std::endl;
  return 0;
}
// Output: 6 13 119 111
Reference: http://en.cppreference.com/w/cpp/utility/functional/bind

No comments:

Post a Comment