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>
4 #include <cassert>
5
6 template<typename Signature>
7 class function;
8
9 template<typename R, typename... Args>
10 class invoker_base
11 {
12 public:
~invoker_base()13 virtual ~invoker_base() { }
14 virtual R invoke(Args...) = 0;
15 virtual invoker_base* clone() = 0;
16 };
17
18 template<typename F, typename R, typename... Args>
19 class functor_invoker : public invoker_base<R, Args...>
20 {
21 public:
functor_invoker(const F & f)22 explicit functor_invoker(const F& f) : f(f) { }
invoke(Args...args)23 R invoke(Args... args) { return f(args...); }
clone()24 functor_invoker* clone() { return new functor_invoker(f); }
25
26 private:
27 F f;
28 };
29
30 template<typename R, typename... Args>
31 class function<R (Args...)> {
32 public:
33 typedef R result_type;
34
function()35 function() : invoker (0) { }
36
function(const function & other)37 function(const function& other) : invoker(0) {
38 if (other.invoker)
39 invoker = other.invoker->clone();
40 }
41
42 template<typename F>
function(const F & f)43 function(const F& f) : invoker(0) {
44 invoker = new functor_invoker<F, R, Args...>(f);
45 }
46
~function()47 ~function() {
48 if (invoker)
49 delete invoker;
50 }
51
52 function& operator=(const function& other) {
53 function(other).swap(*this);
54 return *this;
55 }
56
57 template<typename F>
58 function& operator=(const F& f) {
59 function(f).swap(*this);
60 return *this;
61 }
62
swap(function & other)63 void swap(function& other) {
64 invoker_base<R, Args...>* tmp = invoker;
65 invoker = other.invoker;
66 other.invoker = tmp;
67 }
68
operator()69 result_type operator()(Args... args) const {
70 assert(invoker);
71 return invoker->invoke(args...);
72 }
73
74 private:
75 invoker_base<R, Args...>* invoker;
76 };
77
78 struct plus {
operatorplus79 template<typename T> T operator()(T x, T y) { return x + y; }
80 };
81
82 struct multiplies {
operatormultiplies83 template<typename T> T operator()(T x, T y) { return x * y; }
84 };
85
main()86 int main()
87 {
88 function<int(int, int)> f1 = plus();
89 assert(f1(3, 5) == 8);
90
91 f1 = multiplies();
92 assert(f1(3, 5) == 15);
93
94 return 0;
95 }
96