1 / 14

Function and Bind

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 > {

gasha
Download Presentation

Function and Bind

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Function and Bind Докладчик: Самунь Виктор, МГКН-1

  2. Вспоминаем 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) { … } • };

  3. Пример (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);

  4. ptr_fun, mem_fun, mem_fun_ref • f (x) • x.f () • x->f ()

  5. mem_fun • class X { • void action (void); • }; • list <X *> l; • for_each (l.begin (), l.end (), mem_fun (& X::action));

  6. mem_fun_ref • class X { • void action (void); • }; • list <X> l; • for_each (l.begin (), l.end (), mem_fun_ref(& X::action));

  7. 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 - ???

  8. И вдобавок бага • 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; • }

  9. И что делать? Use boost!

  10. Boost • #include <boost/function.hpp> • #include <boost/bind.hpp>

  11. 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);

  12. 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;

  13. 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

  14. Конец

More Related