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 11 #include <iostream> 12 #include <string> 13 #include <boost/signals2/signal.hpp> 14 #include <boost/bind.hpp> 15 16 //[ document_def_code_snippet 17 class Document 18 { 19 public: 20 typedef boost::signals2::signal<void ()> signal_t; 21 22 public: Document()23 Document() 24 {} 25 26 /* Connect a slot to the signal which will be emitted whenever 27 text is appended to the document. */ connect(const signal_t::slot_type & subscriber)28 boost::signals2::connection connect(const signal_t::slot_type &subscriber) 29 { 30 return m_sig.connect(subscriber); 31 } 32 append(const char * s)33 void append(const char* s) 34 { 35 m_text += s; 36 m_sig(); 37 } 38 getText() const39 const std::string& getText() const 40 { 41 return m_text; 42 } 43 44 private: 45 signal_t m_sig; 46 std::string m_text; 47 }; 48 //] 49 50 //[ text_view_def_code_snippet 51 class TextView 52 { 53 public: TextView(Document & doc)54 TextView(Document& doc): m_document(doc) 55 { 56 m_connection = m_document.connect(boost::bind(&TextView::refresh, this)); 57 } 58 ~TextView()59 ~TextView() 60 { 61 m_connection.disconnect(); 62 } 63 refresh() const64 void refresh() const 65 { 66 std::cout << "TextView: " << m_document.getText() << std::endl; 67 } 68 private: 69 Document& m_document; 70 boost::signals2::connection m_connection; 71 }; 72 //] 73 74 //[ hex_view_def_code_snippet 75 class HexView 76 { 77 public: HexView(Document & doc)78 HexView(Document& doc): m_document(doc) 79 { 80 m_connection = m_document.connect(boost::bind(&HexView::refresh, this)); 81 } 82 ~HexView()83 ~HexView() 84 { 85 m_connection.disconnect(); 86 } 87 refresh() const88 void refresh() const 89 { 90 const std::string& s = m_document.getText(); 91 92 std::cout << "HexView:"; 93 94 for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) 95 std::cout << ' ' << std::hex << static_cast<int>(*it); 96 97 std::cout << std::endl; 98 } 99 private: 100 Document& m_document; 101 boost::signals2::connection m_connection; 102 }; 103 //] 104 105 //[ document_view_main_code_snippet main(int argc,char * argv[])106int main(int argc, char* argv[]) 107 { 108 Document doc; 109 TextView v1(doc); 110 HexView v2(doc); 111 112 doc.append(argc == 2 ? argv[1] : "Hello world!"); 113 return 0; 114 } 115 //] 116