counter.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright (C) 2008-2018 Lorenzo Caminiti
  2. // Distributed under the Boost Software License, Version 1.0 (see accompanying
  3. // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
  4. // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html
  5. //[mitchell02_counter
  6. #ifndef COUNTER_HPP_
  7. #define COUNTER_HPP_
  8. #include "../observer/subject.hpp"
  9. #include <boost/contract.hpp>
  10. class counter
  11. #define BASES public subject
  12. : BASES
  13. {
  14. friend class boost::contract::access;
  15. typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types;
  16. #undef BASES
  17. public:
  18. /* Creation */
  19. // Construct counter with specified value.
  20. explicit counter(int a_value = 10) : value_(a_value) {
  21. boost::contract::check c = boost::contract::constructor(this)
  22. .postcondition([&] {
  23. BOOST_CONTRACT_ASSERT(value() == a_value); // Value set.
  24. })
  25. ;
  26. }
  27. // Destroy counter.
  28. virtual ~counter() {
  29. // Could have omitted contracts here (nothing to check).
  30. boost::contract::check c = boost::contract::destructor(this);
  31. }
  32. /* Queries */
  33. // Current counter value.
  34. int value() const {
  35. // Could have omitted contracts here (nothing to check).
  36. boost::contract::check c = boost::contract::public_function(this);
  37. return value_;
  38. }
  39. /* Commands */
  40. // Decrement counter value.
  41. void decrement() {
  42. boost::contract::old_ptr<int> old_value = BOOST_CONTRACT_OLDOF(value());
  43. boost::contract::check c = boost::contract::public_function(this)
  44. .postcondition([&] {
  45. BOOST_CONTRACT_ASSERT(value() == *old_value - 1); // Decrement.
  46. })
  47. ;
  48. --value_;
  49. notify(); // Notify all attached observers.
  50. }
  51. private:
  52. int value_;
  53. };
  54. #endif // #include guard
  55. //]