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
7 #include <boost/contract.hpp>
8 #include <boost/config.hpp>
11 #ifdef BOOST_GCC // G++ does not support static union members yet.
18 static void static_invariant() { // Static class invariants (as usual).
19 BOOST_CONTRACT_ASSERT(instances() >= 0);
22 void invariant() const { // Class invariants (as usual).
23 BOOST_CONTRACT_ASSERT(i_ > 0);
24 BOOST_CONTRACT_ASSERT(d_ > 0);
27 // Contracts for constructor, as usual but...
28 explicit positive(int x) : d_(0) {
29 // ...unions cannot have bases so constructor preconditions here.
30 boost::contract::constructor_precondition<positive> pre([&] {
31 BOOST_CONTRACT_ASSERT(x > 0);
33 boost::contract::old_ptr<int> old_instances =
34 BOOST_CONTRACT_OLDOF(instances());
35 boost::contract::check c = boost::contract::constructor(this)
37 { int y; get(y); BOOST_CONTRACT_ASSERT(y == x); }
38 BOOST_CONTRACT_ASSERT(instances() == *old_instances + 1);
46 // Contracts for destructor (as usual).
48 boost::contract::old_ptr<int> old_instances =
49 BOOST_CONTRACT_OLDOF(instances());
50 boost::contract::check c = boost::contract::destructor(this)
52 BOOST_CONTRACT_ASSERT(instances() == *old_instances - 1);
59 // Contracts for public function (as usual, but no virtual or override).
60 void get(int& x) const {
61 boost::contract::check c = boost::contract::public_function(this)
63 BOOST_CONTRACT_ASSERT(x > 0);
70 // Contracts for static public function (as usual).
71 static int instances() {
72 boost::contract::check c = boost::contract::public_function<positive>();
84 explicit positive(double x) : d_(0) {
85 // Unions cannot have bases so constructor preconditions here.
86 boost::contract::constructor_precondition<positive> pre([&] {
87 BOOST_CONTRACT_ASSERT(x > 0);
89 boost::contract::old_ptr<int> old_instances =
90 BOOST_CONTRACT_OLDOF(instances());
91 boost::contract::check c = boost::contract::constructor(this)
93 { double y; get(y); BOOST_CONTRACT_ASSERT(y == x); }
94 BOOST_CONTRACT_ASSERT(instances() == *old_instances + 1);
102 void get(double& x) const {
103 boost::contract::check c = boost::contract::public_function(this)
105 BOOST_CONTRACT_ASSERT(x > 0);
112 #ifndef BOOST_GCC // G++ does not support static union members yet.
113 static int instances_;
117 #ifndef BOOST_GCC // G++ does not support static union members yet.
118 int positive::instances_ = 0;
124 assert(p.instances() == 1);
125 { int y = -456; p.get(y); assert(y == 123); }
128 assert(q.instances() == 2);
129 { double y = -4.56; q.get(y); assert(y == 1.23); }
131 assert(positive::instances() == 0);