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