1 // { dg-do run { target c++11 } }
2 // { dg-skip-if "requires hosted libstdc++ for cassert" { ! hostedlib } }
3 // A basic implementation of TR1's function using variadic teplates
4 // Contributed by Douglas Gregor <doug.gregor@gmail.com>
7 template<typename Signature>
10 template<typename R, typename... Args>
14 virtual ~invoker_base() { }
15 virtual R invoke(Args...) = 0;
16 virtual invoker_base* clone() = 0;
19 template<typename F, typename R, typename... Args>
20 class functor_invoker : public invoker_base<R, Args...>
23 explicit functor_invoker(const F& f) : f(f) { }
24 R invoke(Args... args) { return f(args...); }
25 functor_invoker* clone() { return new functor_invoker(f); }
31 template<typename R, typename... Args>
32 class function<R (Args...)> {
34 typedef R result_type;
36 function() : invoker (0) { }
38 function(const function& other) : invoker(0) {
40 invoker = other.invoker->clone();
44 function(const F& f) : invoker(0) {
45 invoker = new functor_invoker<F, R, Args...>(f);
53 function& operator=(const function& other) {
54 function(other).swap(*this);
59 function& operator=(const F& f) {
60 function(f).swap(*this);
64 void swap(function& other) {
65 invoker_base<R, Args...>* tmp = invoker;
66 invoker = other.invoker;
70 result_type operator()(Args... args) const {
72 return invoker->invoke(args...);
76 invoker_base<R, Args...>* invoker;
80 template<typename T> T operator()(T x, T y) { return x + y; }
84 template<typename T> T operator()(T x, T y) { return x * y; }
89 function<int(int, int)> f1 = plus();
90 assert(f1(3, 5) == 8);
93 assert(f1(3, 5) == 15);