Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <functional>
- #include <vector>
- #include <algorithm>
- #include <cstdio>
- void f(int i)
- {
- std::cout << "function f called.\n";
- }
- void g(int i)
- {
- std::cout << "function g called.\n";
- }
- void h(int i)
- {
- std::cout << "function h called.\n";
- }
- template <typename ResultType, typename... Args>
- struct Delegate;
- template <typename ResultType, typename... Args>
- struct Delegate<ResultType(Args...)>
- {
- typedef std::function<ResultType(Args...)> function_type;
- std::vector<function_type> fns;
- Delegate() = default;
- Delegate(std::initializer_list<function_type> l): fns(l) {}
- Delegate& operator +=(const function_type& fn)
- {
- fns.push_back(fn);
- return *this;
- }
- ResultType operator ()(Args... args)
- {
- std::for_each(fns.begin(), fns.end()-1, std::bind(&function_type::operator(), std::placeholders::_1, args...));
- return fns.back()(args...);
- }
- };
- int main()
- {
- Delegate<void (int)> d({f, g});
- d+=h;
- d(1);
- Delegate<int (const char*, int, int, int)> pt({std::printf});
- pt("%d+%d=%d\n", 1, 1, 1+1);
- }
Advertisement
Add Comment
Please, Sign In to add comment