* decl.c (make_typename_type): s/parameters/arguments/.
[official-gcc.git] / gcc / testsuite / g++.dg / cpp0x / variadic-function.C
blobbb98531c3878bb26f9d26327fd322fdfbed1d192
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>
6 template<typename Signature>
7 class function;
9 template<typename R, typename... Args>
10 class invoker_base
12  public:
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...>
21  public:
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); }
26  private:
27   F f;
30 template<typename R, typename... Args>
31 class function<R (Args...)> {
32  public:
33   typedef R result_type;
35   function() : invoker (0) { }
37   function(const function& other) : invoker(0) {
38     if (other.invoker) 
39       invoker = other.invoker->clone();
40   }
42   template<typename F>
43   function(const F& f) : invoker(0) {
44     invoker = new functor_invoker<F, R, Args...>(f); 
45   }
47   ~function() {
48     if (invoker)
49       delete invoker;
50   }
52   function& operator=(const function& other) {
53     function(other).swap(*this);
54     return *this;
55   }
57   template<typename F>
58   function& operator=(const F& f) {
59     function(f).swap(*this);
60     return *this;
61   }
63   void swap(function& other) {
64     invoker_base<R, Args...>* tmp = invoker;
65     invoker = other.invoker;
66     other.invoker = tmp;
67   }
69   result_type operator()(Args... args) const {
70     assert(invoker);
71     return invoker->invoke(args...);
72   }
74  private:
75   invoker_base<R, Args...>* invoker;
78 struct plus {
79   template<typename T> T operator()(T x, T y) { return x + y; }
82 struct multiplies {
83   template<typename T> T operator()(T x, T y) { return x * y; }
86 int main()
88   function<int(int, int)> f1 = plus();
89   assert(f1(3, 5) == 8);
91   f1 = multiplies();
92   assert(f1(3, 5) == 15);
94   return 0;