| 1 |
// { dg-do run { target c++11 } } |
| 2 |
// { dg-skip-if "requires hosted libstdc++ for cassert" { ! hostedlib } } |
| 3 |
// A basic implementation of TR1's mem_fn using variadic teplates |
| 4 |
// Contributed by Douglas Gregor <[email protected]> |
| 5 |
#include <cassert> |
| 6 |
|
| 7 |
template<typename R, typename Class, typename... Args> |
| 8 |
class Mem_fn |
| 9 |
{ |
| 10 |
public: |
| 11 |
explicit Mem_fn(R (Class::*pmf)(Args...)) : pmf(pmf) { } |
| 12 |
|
| 13 |
R operator()(Class& object, Args... args) |
| 14 |
{ |
| 15 |
return (object.*pmf)(args...); |
| 16 |
} |
| 17 |
|
| 18 |
R operator()(Class* object, Args... args) |
| 19 |
{ |
| 20 |
return (object->*pmf)(args...); |
| 21 |
} |
| 22 |
|
| 23 |
R (Class::*pmf)(Args...); |
| 24 |
}; |
| 25 |
|
| 26 |
template<typename R, typename Class, typename... Args> |
| 27 |
inline Mem_fn<R, Class, Args...> |
| 28 |
mem_fn(R (Class::* pmf)(Args...)) |
| 29 |
{ |
| 30 |
return Mem_fn<R, Class, Args...>(pmf); |
| 31 |
} |
| 32 |
|
| 33 |
class X { |
| 34 |
public: |
| 35 |
int negate(int x) { return -x; } |
| 36 |
int plus(int x, int y) { return x + y; } |
| 37 |
}; |
| 38 |
|
| 39 |
int main() |
| 40 |
{ |
| 41 |
X x; |
| 42 |
X* xp = &x; |
| 43 |
|
| 44 |
assert(mem_fn(&X::negate)(x, 17) == -17); |
| 45 |
assert(mem_fn(&X::negate)(xp, 17) == -17); |
| 46 |
assert(mem_fn(&X::plus)(x, 17, 25) == 42); |
| 47 |
assert(mem_fn(&X::plus)(xp, 17, 25) == 42); |
| 48 |
|
| 49 |
return 0; |
| 50 |
} |