doc_view.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. // Document/View sample for Boost.Signals
  2. // Copyright Keith MacDonald 2005.
  3. // Copyright Frank Mori Hess 2009.
  4. //
  5. // Use, modification and
  6. // distribution is subject to the Boost Software License, Version
  7. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  8. // http://www.boost.org/LICENSE_1_0.txt)
  9. // For more information, see http://www.boost.org
  10. #include <iostream>
  11. #include <string>
  12. #include <boost/signals2/signal.hpp>
  13. #include <boost/bind.hpp>
  14. //[ document_def_code_snippet
  15. class Document
  16. {
  17. public:
  18. typedef boost::signals2::signal<void ()> signal_t;
  19. public:
  20. Document()
  21. {}
  22. /* Connect a slot to the signal which will be emitted whenever
  23. text is appended to the document. */
  24. boost::signals2::connection connect(const signal_t::slot_type &subscriber)
  25. {
  26. return m_sig.connect(subscriber);
  27. }
  28. void append(const char* s)
  29. {
  30. m_text += s;
  31. m_sig();
  32. }
  33. const std::string& getText() const
  34. {
  35. return m_text;
  36. }
  37. private:
  38. signal_t m_sig;
  39. std::string m_text;
  40. };
  41. //]
  42. //[ text_view_def_code_snippet
  43. class TextView
  44. {
  45. public:
  46. TextView(Document& doc): m_document(doc)
  47. {
  48. m_connection = m_document.connect(boost::bind(&TextView::refresh, this));
  49. }
  50. ~TextView()
  51. {
  52. m_connection.disconnect();
  53. }
  54. void refresh() const
  55. {
  56. std::cout << "TextView: " << m_document.getText() << std::endl;
  57. }
  58. private:
  59. Document& m_document;
  60. boost::signals2::connection m_connection;
  61. };
  62. //]
  63. //[ hex_view_def_code_snippet
  64. class HexView
  65. {
  66. public:
  67. HexView(Document& doc): m_document(doc)
  68. {
  69. m_connection = m_document.connect(boost::bind(&HexView::refresh, this));
  70. }
  71. ~HexView()
  72. {
  73. m_connection.disconnect();
  74. }
  75. void refresh() const
  76. {
  77. const std::string& s = m_document.getText();
  78. std::cout << "HexView:";
  79. for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
  80. std::cout << ' ' << std::hex << static_cast<int>(*it);
  81. std::cout << std::endl;
  82. }
  83. private:
  84. Document& m_document;
  85. boost::signals2::connection m_connection;
  86. };
  87. //]
  88. //[ document_view_main_code_snippet
  89. int main(int argc, char* argv[])
  90. {
  91. Document doc;
  92. TextView v1(doc);
  93. HexView v2(doc);
  94. doc.append(argc == 2 ? argv[1] : "Hello world!");
  95. return 0;
  96. }
  97. //]