Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++) Binder

 

A binder is a type of adapter that allows a two-argument function object to be used as a single-argument function by binding one argument to a value [0] . Binders are useful when using algorithms.

 

There are two STL binders:

  • std::bind1st

  • std::bind2nd

    There is one Boost binder:

  • boost::bind

     

    Using boost::bind results in easier to read and shorter code.

     

     

    Replacing a for loop by algorithms using std::bind2nd and boost::bind

     

     

    #include <vector>

     

    struct Widget

    {

    void DoItOften(const int n) const { /* do it n times */ }

    };

     

    void DoItOften(const std::vector<Widget>& v, const int n)

    {

    const int sz = v.size();

    for (int i=0; i!=sz; ++i)

    {

    v[i].DoItOften(n);

    }

    }

     

     

     

     

    #include <vector>

    #include <algorithm>

    #include <numeric>

     

    struct Widget

    {

    void DoItOften(const int n) const { /* do it n times */ }

    };

     

    void DoItOften(const std::vector<Widget>& v, const int n)

    {

    std::for_each(v.begin(),v.end(),

    std::bind2nd(std::mem_fun_ref(&Widget::DoItOften),n));

    }

     

     

     

     

     

    #include <vector>

    #include <algorithm>

    #include <boost/bind.hpp>

     

    struct Widget

    {

    void DoItOften(const int n) const { /* do it n times */ }

    };

     

    void DoItOften(const std::vector<Widget>& v, const int n)

    {

    std::for_each(v.begin(),v.end(),

    boost::bind(&Widget::DoItOften, _1, n));

    }

     

     

     

    References

    [0]   Bjarne Stroustrup . The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.4.4: 'A binder allows a two-argument function object to be used as a single-argument function by binding one argument to a value.'

     

     

    Go back to Richel Bilderbeek's C++ page.

    Go back to Richel Bilderbeek's homepage.