(C++) Binder
January 9, 2018 · View on GitHub
(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 [1]. Binders are useful when using algorithms.
Using boost::bind results in easier to read and shorter code.
Replacing a for loop by an algorithm 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 std::size_t sz = v.size(); for (int i=0; i!=sz; ++i) { v[i].DoItOften(n); } }
#include <algorithm> #include <numeric> #include <vector> 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 <algorithm> #include <vector> #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) ); }
Advice
- Prefer Lambda expressions over binders [2]
References
- 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.'
- Scott Meyers. C++ And Beyond 2012 session: 'Initial thoughts on Effective C++11'. 2012. 'Prefer Lambdas over Binders'