fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3. #include <type_traits>
  4.  
  5. template <class F>
  6. struct Decomposer;
  7.  
  8. template <class R, class A>
  9. struct Decomposer<R (A)>
  10. {
  11. typedef R return_type;
  12. typedef A argument_type;
  13. };
  14.  
  15.  
  16. template <class F>
  17. struct my_function
  18. {
  19. typedef typename Decomposer<F>::return_type return_type;
  20. typedef typename Decomposer<F>::argument_type argument_type;
  21.  
  22. return_type operator() (argument_type arg) const {
  23. return (*impl)(arg);
  24. }
  25.  
  26. template <class From>
  27. my_function(From &&from)
  28. {
  29. struct ConcreteImpl : Impl
  30. {
  31. typename std::remove_reference<From>::type functor;
  32. ConcreteImpl(From &&functor) : functor(std::forward<From>(functor)) {}
  33. virtual return_type operator() (argument_type arg) const override
  34. {
  35. return functor(arg);
  36. }
  37. };
  38. impl.reset(new ConcreteImpl(std::forward<From>(from)));
  39. }
  40.  
  41. private:
  42. struct Impl {
  43. virtual ~Impl() {}
  44. virtual return_type operator() (argument_type arg) const = 0;
  45. };
  46.  
  47. std::unique_ptr<Impl> impl;
  48. };
  49.  
  50.  
  51. int main(int argc, char* argv[])
  52. {
  53. int mybool = 5;
  54.  
  55. auto foo = [&] (int arg) {
  56. return mybool * arg;
  57. };
  58.  
  59. my_function<int(int)> foo2 = foo;
  60.  
  61. int result = foo2(42);
  62.  
  63. std::cout << result << std::endl;
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
210