fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. class A {
  5. public:
  6. void foo (int x) { std::cout << "A::foo(" << x << ")\n"; }
  7. };
  8.  
  9. class B {
  10. public:
  11. void foo (int x) { std::cout << "B::foo(" << x << ")\n"; }
  12. };
  13.  
  14. // Variante 1: std::bind
  15. void test1 () {
  16. // Instanzen der Klassen
  17. A a;
  18. B b;
  19.  
  20. // "Polymorpher" Funktionspointer
  21. std::function<void(int)> fun;
  22.  
  23. // Weise A::foo zu, mit Instanz a
  24. fun = std::bind (&A::foo, &a, std::placeholders::_1);
  25.  
  26. // Rufe auf
  27. fun (42);
  28.  
  29. // Weise B::foo zu, mit Instanz b
  30. fun = std::bind (&B::foo, &b, std::placeholders::_1);
  31.  
  32. // Rufe auf
  33. fun (84);
  34. }
  35.  
  36. // Variante 2: Lambda
  37. void test2 () {
  38. // Instanzen der Klassen
  39. A a;
  40. B b;
  41.  
  42. // "Polymorpher" Funktionspointer
  43. std::function<void(int)> fun;
  44.  
  45. // Weise A::foo zu, mit Instanz a
  46. fun = [&a] (int x) { a.foo (x); };
  47.  
  48. // Rufe auf
  49. fun (42);
  50.  
  51. // Weise B::foo zu, mit Instanz b
  52. fun = [&b] (int x) { b.foo (x); };
  53.  
  54. // Rufe auf
  55. fun (84);
  56. }
  57.  
  58. int main() {
  59. test1 ();
  60. test2 ();
  61. return 0;
  62. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
A::foo(42)
B::foo(84)
A::foo(42)
B::foo(84)