fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. template <typename OBJ>
  5. int foo(int n, OBJ o)
  6. {
  7. int x = 0;
  8. for (int i = 0; i < n; ++i) {
  9. x += o[i];
  10. }
  11. return x;
  12. }
  13.  
  14. template <typename> struct Functor;
  15.  
  16. template <typename R> struct Functor<R(int)>
  17. {
  18. using ftype = std::function<R(int)>;
  19. Functor(ftype f) : f_(f) {}
  20.  
  21. R operator[](int i) const { return f_(i); }
  22.  
  23. ftype f_;
  24. };
  25.  
  26. int main()
  27. {
  28. Functor<int(int)> f = {[](int i) -> int {return i*i;}};
  29. std::cout << foo(10, f) << std::endl;
  30. }
  31.  
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
285