fork download
  1. #include <memory>
  2. #include <utility>
  3.  
  4. template <typename T>
  5. struct function;
  6.  
  7. template <typename R, typename... A>
  8. struct function<R(A...)> {
  9. struct inner_fun_base {
  10. virtual R call(A...) = 0;
  11. };
  12.  
  13. template <typename F>
  14. struct inner_fun : inner_fun_base {
  15. inner_fun(F f) : f(f) {}
  16. F f;
  17. virtual R call(A... a) {
  18. return f(std::forward<A>(a)...);
  19. }
  20. };
  21.  
  22. std::unique_ptr<inner_fun_base> ptr;
  23.  
  24. template <typename F>
  25. function(F f) // I'm going by value here for simplicity
  26. :ptr(new inner_fun<F>(f)) {}
  27.  
  28. R operator()(A... a) {
  29. return ptr->call(std::forward<A>(a)...);
  30. }
  31. };
  32.  
  33. #include <iostream>
  34.  
  35. int main() {
  36. function<bool(int)> f([](int n) { return n > 3; });
  37. std::cout << f(2) << f(4);
  38. }
  39.  
Success #stdin #stdout 0s 3016KB
stdin
Standard input is empty
stdout
01