fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <functional>
  4. #include <vector>
  5.  
  6. class Elem
  7. {
  8. private:
  9. int value_;
  10. std::function<void(const std::string&)> callback_;
  11.  
  12. public:
  13. Elem(int v, std::function<void(const std::string&)> cb)
  14. : value_{v}, callback_{cb}
  15. {}
  16.  
  17. void some_function() const
  18. {
  19. callback_("Elem with value " + std::to_string(value_));
  20. }
  21. };
  22.  
  23. class Cont
  24. {
  25. private:
  26. std::vector<Elem> elements_;
  27.  
  28. void private_function(const std::string& s)
  29. {
  30. std::cout << "In private function: " << s << '\n';
  31. }
  32.  
  33. public:
  34. void add_value(const int v)
  35. {
  36. elements_.push_back(Elem(v, std::bind(&Cont::private_function, this, std::placeholders::_1)));
  37. }
  38.  
  39. std::vector<Elem>::const_iterator begin() const
  40. {
  41. return std::begin(elements_);
  42. }
  43.  
  44. std::vector<Elem>::const_iterator end() const
  45. {
  46. return std::end(elements_);
  47. }
  48. };
  49.  
  50. int main()
  51. {
  52. Cont c;
  53.  
  54. // Add some elements
  55. for (int i = 1; i <= 10; ++i)
  56. c.add_value(i);
  57.  
  58. // Call callback function
  59. for (const auto& e : c)
  60. e.some_function();
  61. }
  62.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
In private function: Elem with value 1
In private function: Elem with value 2
In private function: Elem with value 3
In private function: Elem with value 4
In private function: Elem with value 5
In private function: Elem with value 6
In private function: Elem with value 7
In private function: Elem with value 8
In private function: Elem with value 9
In private function: Elem with value 10