fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. int foo(int i)
  5. {
  6. return i*2;
  7. }
  8.  
  9. template <typename Ax, typename R, typename... A>
  10. struct Wrap
  11. {
  12. typedef R (*F)(A...);
  13. typedef std::function<R(A...)> Ftor;
  14.  
  15. Wrap(F f) : _f(f) { }
  16. Wrap(const Ftor& f) : _f(f) { }
  17.  
  18. R operator()(Ax extra, A... a) const
  19. { return _f(a...); /*just forward*/ }
  20.  
  21. Ftor _f;
  22. };
  23.  
  24. template <typename Ax=int, typename R, typename... A>
  25. std::function<R(Ax, A...)> wrap(R (f)(A...))
  26. {
  27. return Wrap<Ax,R,A...>(f);
  28. }
  29.  
  30. template <typename Ax=int, typename R, typename... A>
  31. std::function<R(Ax, A...)> wrap(std::function<R(A...)> functor)
  32. {
  33. return Wrap<Ax,R,A...>(functor);
  34. }
  35.  
  36. int main(int argc, const char *argv[])
  37. {
  38. auto bar = wrap(foo);
  39. std::function<int(int, int)> barfunc = wrap(foo);
  40.  
  41. std::cout << barfunc(-999, 21) << std::endl;
  42.  
  43. // wrap the barfunc?
  44. auto rewrap = wrap(barfunc);
  45. std::cout << rewrap(-999, -999, 21) << std::endl;
  46.  
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 2964KB
stdin
Standard input is empty
stdout
42
42