fork(3) download
  1. #include <functional>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5.  
  6. class Test
  7. {
  8. public:
  9. Test (int testType) : m_testType(testType) {};
  10. void blah() { std::cout << "BLAH! " << m_testType << std::endl; }
  11. void blahWithParmeter(std::string p) { std::cout << "BLAH1! Parameter=" << p << std::endl; }
  12. void blahWithParmeter2(std::string p) { std::cout << "BLAH2! Parameter=" << p << std::endl; }
  13.  
  14. private:
  15. int m_testType;
  16.  
  17. };
  18.  
  19. class Bim
  20. {
  21. public:
  22. void operator()(){ std::cout << "BIM!" << std::endl; }
  23. };
  24.  
  25. void boum() { std::cout << "BOUM!" << std::endl; }
  26.  
  27.  
  28. int main()
  29. {
  30. // store the member function of an object:
  31. Test test(7);
  32. //std::function< void() > callback = std::bind( &Test::blah, test );
  33. std::function< void() > callback = std::bind( &Test::blah, test );
  34. callback();
  35.  
  36. // store a callable object (by copy)
  37. callback = Bim{};
  38. callback();
  39.  
  40. // store the address of a static funtion
  41. callback = &boum;
  42. callback();
  43.  
  44. // store a copy of a lambda (that is a callable object)
  45. callback = [&]{ test.blah(); }; // might be clearer than calling std::bind()
  46. callback();
  47.  
  48. // example of callback with parameter using a vector
  49. typedef std::function<void(std::string&)> TstringCallback;
  50.  
  51. std::vector <TstringCallback> callbackListStringParms;
  52. callbackListStringParms.push_back( [&] (const std::string& tag) { test.blahWithParmeter(tag); });
  53. callbackListStringParms.push_back( [&] (const std::string& tag) { test.blahWithParmeter2(tag); });
  54.  
  55. std::string parm1 = "parm1";
  56. std::string parm2 = "parm2";
  57. int i = 0;
  58. for (auto cb : callbackListStringParms )
  59. {
  60. ++i;
  61. if (i == 1)
  62. cb(parm1);
  63. else
  64. cb(parm2);
  65.  
  66. }
  67. }
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
BLAH! 7
BIM!
BOUM!
BLAH! 7
BLAH1! Parameter=parm1
BLAH2! Parameter=parm2