fork download
  1. #include <functional>
  2. #include <iostream>
  3. #include <sstream>
  4. #include <string>
  5. #include <vector>
  6.  
  7. struct buf_rx
  8. {
  9. using callback_type = std::function<void(std::string)> ;
  10.  
  11. void receive(std::istringstream in)
  12. {
  13. std::string word;
  14. while (in >> word)
  15. for (auto func : _cb)
  16. func(word);
  17. }
  18.  
  19. void register_cb(callback_type cb_func)
  20. {
  21. _cb.push_back(cb_func);
  22. }
  23.  
  24. private:
  25. std::vector<callback_type> _cb;
  26. };
  27.  
  28. void string_processor(const std::string& s)
  29. {
  30. std::cout << "string_processor: " << s << '\n';
  31. }
  32.  
  33. struct some_type
  34. {
  35. some_type() :_id(id++) {}
  36.  
  37. void process_string(const std::string& s) {
  38. std::cout << "some_type (" << _id << "): " << s << '\n';
  39. }
  40.  
  41. private:
  42. static unsigned id;
  43. unsigned _id;
  44. };
  45.  
  46. unsigned some_type::id = 0;
  47.  
  48. int main()
  49. {
  50. some_type a;
  51. some_type b;
  52.  
  53. buf_rx buffer;
  54. buffer.register_cb(string_processor);
  55. buffer.register_cb([&](std::string s) {a.process_string(s); });
  56. buffer.register_cb([&](std::string s) {b.process_string(s); });
  57.  
  58. buffer.receive(std::istringstream { "a b c d e" });
  59. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
string_processor: a
some_type (0): a
some_type (1): a
string_processor: b
some_type (0): b
some_type (1): b
string_processor: c
some_type (0): c
some_type (1): c
string_processor: d
some_type (0): d
some_type (1): d
string_processor: e
some_type (0): e
some_type (1): e