zhangsongcui

Practice using template

May 11th, 2011
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. #include <iostream>
  2. #include <functional>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <cstdio>
  6.  
  7. void f(int i)
  8. {
  9.     std::cout << "function f called.\n";
  10. }
  11.  
  12. void g(int i)
  13. {
  14.     std::cout << "function g called.\n";
  15. }
  16.  
  17. void h(int i)
  18. {
  19.     std::cout << "function h called.\n";
  20. }
  21.  
  22. template <typename ResultType, typename... Args>
  23. struct Delegate;
  24.  
  25. template <typename ResultType, typename... Args>
  26. struct Delegate<ResultType(Args...)>
  27. {
  28.     typedef std::function<ResultType(Args...)> function_type;
  29.     std::vector<function_type> fns;
  30.  
  31.     Delegate() = default;
  32.     Delegate(std::initializer_list<function_type> l): fns(l) {}
  33.     Delegate& operator +=(const function_type& fn)
  34.     {
  35.         fns.push_back(fn);
  36.         return *this;
  37.     }
  38.  
  39.     ResultType operator ()(Args... args)
  40.     {
  41.         std::for_each(fns.begin(), fns.end()-1, std::bind(&function_type::operator(), std::placeholders::_1, args...));
  42.         return fns.back()(args...);
  43.     }
  44. };
  45.  
  46. int main()
  47. {
  48.     Delegate<void (int)> d({f, g});
  49.     d+=h;
  50.     d(1);
  51.     Delegate<int (const char*, int, int, int)> pt({std::printf});
  52.     pt("%d+%d=%d\n", 1, 1, 1+1);
  53. }
Advertisement
Add Comment
Please, Sign In to add comment