140 likes | 247 Views
Function and Bind. Докладчик: Самунь Виктор, МГКН-1. Вспоминаем STL. #include <functional> #include <algorithm> class my_func : public unary_function < int , int > { int operator () ( int p) { … } }; class my_func_2 : public binary_function < int , int , int > {
E N D
Function and Bind Докладчик: Самунь Виктор, МГКН-1
Вспоминаем STL • #include <functional> • #include <algorithm> • class my_func : public unary_function <int, int> { • int operator () (int p) { … }}; • class my_func_2 : public binary_function <int, int, int> { • int operator () (int r, int l) { … } • };
Пример (STL) • class my_func : public unary_function <int, int> { • int operator () (int p) { cout << (p * 2 – 1) << endl; }}; • ... • vector <int> v; • my_func f; • ... • for_each <vector<int>::iterator, my_func &> • (v.begin (), v.end (), f);
ptr_fun, mem_fun, mem_fun_ref • f (x) • x.f () • x->f ()
mem_fun • class X { • void action (void); • }; • list <X *> l; • for_each (l.begin (), l.end (), mem_fun (& X::action));
mem_fun_ref • class X { • void action (void); • }; • list <X> l; • for_each (l.begin (), l.end (), mem_fun_ref(& X::action));
Binds • bind1st (const Op & f, const Type & left) • -> f’ (x) = f (left, x) • bind2nd (const Op & f, const Type & right) • -> f’(x) = f (x, right) • bind3rd - ???
И вдобавок бага • class X { • public: • intfunc (int & a) { return a + 1; } • }; • int main (void) { • using namespace std; • vector <X *> v; • intp = 1; • for_each(v.begin (), v.end (), bind2nd (mem_fun (& X::func), p)); • return 0; • }
И что делать? Use boost!
Boost • #include <boost/function.hpp> • #include <boost/bind.hpp>
boost::function • boost::function_n <ret, p1, ..., pn> instance; • boost::function2 <int, int, int> my_f; • // boost::function <int (int, int)> my_f; • int f (int a, int b) { return a + b; } • ... • my_f = & f; • cout << my_f (2, 2);
boost::bind • int f (int a, int b) { return a % b; } • ... • boost::function <int (int)> odd = boost::bind (f, _1, 2); • cout << odd (3) << ‘ ’ << odd (4) << endl;
boost::bind and boost::mem_fn • bind (& X::f, a) bind <R> (mem_fn (& X::f), a) • boost::mem_fn = std::mem_fun + std::mem_fun_ref