fork download
  1. #include <functional>
  2. #include <iostream>
  3.  
  4. template<class>
  5. class ProxyFunction;
  6.  
  7.  
  8. template<class R>
  9. class ProxyFunction<R()>
  10. {
  11. std::function<R()> f;
  12.  
  13. public:
  14. ProxyFunction(std::function<R()> f) : f(f) {}
  15. ~ProxyFunction() {
  16. f();
  17. }
  18. operator R() {
  19. return f();
  20. }
  21. };
  22.  
  23.  
  24. template<class R, class FirstArg, class ...MoreArgs>
  25. class ProxyFunction<R(FirstArg, MoreArgs...)>
  26. {
  27. std::function<R(FirstArg, MoreArgs...)> f;
  28.  
  29. public:
  30. ProxyFunction(std::function<R(FirstArg, MoreArgs...)> f) : f(f) {}
  31. ~ProxyFunction() {}
  32.  
  33. ProxyFunction<R(MoreArgs...)> operator <<(const FirstArg &a) {
  34. return ProxyFunction<R(MoreArgs...)>([a,this](MoreArgs... moreArgs) {
  35. return f(a, moreArgs...);
  36. });
  37. }
  38. };
  39.  
  40.  
  41.  
  42.  
  43. template<class R, class ...Args>
  44. auto makeProxy(const std::function<R(Args...)> & f) -> ProxyFunction<R(Args...)> {
  45. return ProxyFunction<R(Args...)>(f);
  46. }
  47. template<class R, class ...Args>
  48. auto makeProxy(R (*f)(Args...)) -> ProxyFunction<R(Args...)> {
  49. return ProxyFunction<R(Args...)>(std::function<R(Args...)>(f));
  50. }
  51.  
  52.  
  53.  
  54. int add(int a, int b) {
  55. return a + b;
  56. }
  57.  
  58.  
  59.  
  60. int main() {
  61. int a = 42;
  62. int b = 10;
  63. auto f = makeProxy(&add);
  64. std::cout << (f << a << b) << std::endl;
  65. }
  66.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
52