fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template<class FUNC>
  5. class IndexFunctor
  6. {
  7. public:
  8. typedef FUNC FUNC_T;
  9.  
  10. explicit IndexFunctor(const FUNC_T& func) : func(func), index(0) {}
  11.  
  12. private:
  13. FUNC_T func;
  14. int index;
  15.  
  16. public:
  17. template<typename... Args>
  18. auto operator ()(Args&&... args)
  19. -> decltype(func(std::forward<Args>(args)..., index++)) //get return type
  20. {
  21. return func(std::forward<Args>(args)..., index++);
  22. }
  23.  
  24. const FUNC_T& GetFunctor() const
  25. {
  26. return func;
  27. }
  28.  
  29. int GetIndex() const
  30. {
  31. return index;
  32. }
  33.  
  34. void SetIndex(int index)
  35. {
  36. this->index = index;
  37. }
  38.  
  39. };
  40.  
  41. template<class FUNC>
  42. IndexFunctor<FUNC> with_index(const FUNC& func)
  43. {
  44. return IndexFunctor<FUNC>(func);
  45. }
  46.  
  47. int main()
  48. {
  49. auto f = with_index([](int a, int index){ return a * index; });
  50. int a = f(5);
  51. cout << a << endl;
  52. }
  53.  
Success #stdin #stdout 0s 3340KB
stdin
1
2
10
42
11
stdout
0