fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. using namespace std;
  5.  
  6. class Test {
  7. std::function<int(Test*)> func;
  8. public:
  9. int operator()() { return func(this); }
  10.  
  11. int DoIt1() {
  12. return 1;
  13. }
  14.  
  15. int DoIt2() {
  16. return 2;
  17. }
  18.  
  19. void SetIt(int i) {
  20. if(i == 1) {
  21. func = &Test::DoIt1;
  22. } else {
  23. func = &Test::DoIt2;
  24. }
  25. }
  26. };
  27.  
  28. int main()
  29. {
  30. Test t1;
  31.  
  32. t1.SetIt(1);
  33.  
  34. std::cout << t1() << std::endl;
  35.  
  36. t1.SetIt(2);
  37.  
  38. std::cout << t1() << std::endl;
  39.  
  40. return 0;
  41. }
Success #stdin #stdout 0s 2828KB
stdin
Standard input is empty
stdout
1
2