postconstructor_ex2.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // An example of defining a postconstructor for a class which
  2. // uses boost::signals2::deconstruct as its factory function.
  3. // This example expands on the basic postconstructor_ex1.cpp example
  4. // by passing arguments to the constructor and postconstructor.
  5. //
  6. // Copyright Frank Mori Hess 2009.
  7. // Use, modification and
  8. // distribution is subject to the Boost Software License, Version
  9. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  10. // http://www.boost.org/LICENSE_1_0.txt)
  11. // For more information, see http://www.boost.org
  12. #include <boost/shared_ptr.hpp>
  13. #include <boost/signals2/deconstruct.hpp>
  14. #include <iostream>
  15. #include <sstream>
  16. #include <string>
  17. namespace bs2 = boost::signals2;
  18. namespace mynamespace
  19. {
  20. class Y
  21. {
  22. public:
  23. /* This adl_postconstruct function will be found
  24. via argument-dependent lookup when using boost::signals2::deconstruct. */
  25. template<typename T> friend
  26. void adl_postconstruct(const boost::shared_ptr<T> &, Y *y, const std::string &text)
  27. {
  28. y->_text_stream << text;
  29. }
  30. void print() const
  31. {
  32. std::cout << _text_stream.str() << std::endl;
  33. }
  34. private:
  35. friend class bs2::deconstruct_access; // give boost::signals2::deconstruct access to private constructor
  36. // private constructor forces use of boost::signals2::deconstruct to create objects.
  37. Y(const std::string &text)
  38. {
  39. _text_stream << text;
  40. }
  41. std::ostringstream _text_stream;
  42. };
  43. }
  44. int main()
  45. {
  46. boost::shared_ptr<mynamespace::Y> y = bs2::deconstruct<mynamespace::Y>("Hello, ").postconstruct("world!");
  47. y->print();
  48. return 0;
  49. }