1 // { dg-do run { target c++11 } }
2 // A basic implementation of TR1's function using variadic teplates
3 // Contributed by Douglas Gregor <doug.gregor@gmail.com>
6 template<typename Signature>
9 template<typename R, typename... Args>
13 virtual ~invoker_base() { }
14 virtual R invoke(Args...) = 0;
15 virtual invoker_base* clone() = 0;
18 template<typename F, typename R, typename... Args>
19 class functor_invoker : public invoker_base<R, Args...>
22 explicit functor_invoker(const F& f) : f(f) { }
23 R invoke(Args... args) { return f(args...); }
24 functor_invoker* clone() { return new functor_invoker(f); }
30 template<typename R, typename... Args>
31 class function<R (Args...)> {
33 typedef R result_type;
35 function() : invoker (0) { }
37 function(const function& other) : invoker(0) {
39 invoker = other.invoker->clone();
43 function(const F& f) : invoker(0) {
44 invoker = new functor_invoker<F, R, Args...>(f);
52 function& operator=(const function& other) {
53 function(other).swap(*this);
58 function& operator=(const F& f) {
59 function(f).swap(*this);
63 void swap(function& other) {
64 invoker_base<R, Args...>* tmp = invoker;
65 invoker = other.invoker;
69 result_type operator()(Args... args) const {
71 return invoker->invoke(args...);
75 invoker_base<R, Args...>* invoker;
79 template<typename T> T operator()(T x, T y) { return x + y; }
83 template<typename T> T operator()(T x, T y) { return x * y; }
88 function<int(int, int)> f1 = plus();
89 assert(f1(3, 5) == 8);
92 assert(f1(3, 5) == 15);