fork(1) download
  1. #include <iostream>
  2. struct CallIntDelegate
  3. {
  4. virtual void operator()(int i) const = 0;
  5. };
  6.  
  7. template<typename O, void (O::*func)(int)>
  8. struct IntCaller : public CallIntDelegate
  9. {
  10. IntCaller(O* obj) : object(obj) {}
  11. void operator()(int i) const
  12. {
  13. // This line can easily optimized by the compiler
  14. // in object->func(i) (= normal function call, not pointer-to-member call)
  15. // Pointer-to-member calls are slower than regular function calls
  16. (object->*func)(i);
  17. }
  18. private:
  19. O* object;
  20. };
  21.  
  22. void set(const CallIntDelegate& setValue)
  23. {
  24. setValue(42);
  25. }
  26.  
  27. class test
  28. {
  29. public:
  30. void printAnswer(int i)
  31. {
  32. std::cout << "The answer is " << 2 * i << "\n";
  33. }
  34. };
  35.  
  36. int main()
  37. {
  38. test obj;
  39. set(IntCaller<test,&test::printAnswer>(&obj));
  40. }
Success #stdin #stdout 0.01s 2680KB
stdin
Standard input is empty
stdout
The answer is 84