1 // { dg-do run }
2 // { dg-options "-std=gnu++0x" }
3 // A basic implementation of TR1's function using variadic teplates
4 // Contributed by Douglas Gregor <doug.gregor@gmail.com>
5 #include <cassert>
6
7 template<typename Signature>
8 class function;
9
10 template<typename R, typename... Args>
11 class invoker_base
12 {
13 public:
~invoker_base()14 virtual ~invoker_base() { }
15 virtual R invoke(Args...) = 0;
16 virtual invoker_base* clone() = 0;
17 };
18
19 template<typename F, typename R, typename... Args>
20 class functor_invoker : public invoker_base<R, Args...>
21 {
22 public:
functor_invoker(const F & f)23 explicit functor_invoker(const F& f) : f(f) { }
invoke(Args...args)24 R invoke(Args... args) { return f(args...); }
clone()25 functor_invoker* clone() { return new functor_invoker(f); }
26
27 private:
28 F f;
29 };
30
31 template<typename R, typename... Args>
32 class function<R (Args...)> {
33 public:
34 typedef R result_type;
35
function()36 function() : invoker (0) { }
37
function(const function & other)38 function(const function& other) : invoker(0) {
39 if (other.invoker)
40 invoker = other.invoker->clone();
41 }
42
43 template<typename F>
function(const F & f)44 function(const F& f) : invoker(0) {
45 invoker = new functor_invoker<F, R, Args...>(f);
46 }
47
~function()48 ~function() {
49 if (invoker)
50 delete invoker;
51 }
52
53 function& operator=(const function& other) {
54 function(other).swap(*this);
55 return *this;
56 }
57
58 template<typename F>
59 function& operator=(const F& f) {
60 function(f).swap(*this);
61 return *this;
62 }
63
swap(function & other)64 void swap(function& other) {
65 invoker_base<R, Args...>* tmp = invoker;
66 invoker = other.invoker;
67 other.invoker = tmp;
68 }
69
operator()70 result_type operator()(Args... args) const {
71 assert(invoker);
72 return invoker->invoke(args...);
73 }
74
75 private:
76 invoker_base<R, Args...>* invoker;
77 };
78
79 struct plus {
operatorplus80 template<typename T> T operator()(T x, T y) { return x + y; }
81 };
82
83 struct multiplies {
operatormultiplies84 template<typename T> T operator()(T x, T y) { return x * y; }
85 };
86
main()87 int main()
88 {
89 function<int(int, int)> f1 = plus();
90 assert(f1(3, 5) == 8);
91
92 f1 = multiplies();
93 assert(f1(3, 5) == 15);
94
95 return 0;
96 }
97