• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 //[n1962_circle
8 #include <boost/contract.hpp>
9 #include <cassert>
10 
11 class shape {
12 public:
~shape()13     virtual ~shape() {}
14 
15     virtual unsigned compute_area(boost::contract::virtual_* v = 0) const = 0;
16 };
17 
compute_area(boost::contract::virtual_ * v) const18 unsigned shape::compute_area(boost::contract::virtual_* v) const {
19     unsigned result;
20     boost::contract::check c = boost::contract::public_function(v, result, this)
21         .postcondition([&] (int const& result) {
22             BOOST_CONTRACT_ASSERT(result > 0);
23         })
24     ;
25     assert(false);
26     return result;
27 }
28 
29 class circle
30     #define BASES public shape
31     : BASES
32 {
33     friend class boost::contract::access;
34 
35     typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types;
36     #undef BASES
37 
38     BOOST_CONTRACT_OVERRIDE(compute_area);
39 
40 public:
41     static int const pi = 3; // Truncated to int from 3.14...
42 
circle(unsigned a_radius)43     explicit circle(unsigned a_radius) : radius_(a_radius) {
44         boost::contract::check c = boost::contract::constructor(this)
45             .postcondition([&] {
46                 BOOST_CONTRACT_ASSERT(radius() == a_radius);
47             })
48         ;
49     }
50 
compute_area(boost::contract::virtual_ * v=0) const51     virtual unsigned compute_area(boost::contract::virtual_* v = 0) const
52             /* override */ {
53         unsigned result;
54         boost::contract::check c = boost::contract::public_function<
55                 override_compute_area>(v, result, &circle::compute_area, this)
56             .postcondition([&] (unsigned const& result) {
57                 BOOST_CONTRACT_ASSERT(result == pi * radius() * radius());
58             })
59         ;
60 
61         return result = pi * radius() * radius();
62     }
63 
radius() const64     unsigned radius() const {
65         boost::contract::check c = boost::contract::public_function(this);
66         return radius_;
67     }
68 
69 private:
70     unsigned radius_;
71 };
72 
main()73 int main() {
74     circle c(2);
75     assert(c.radius() == 2);
76     assert(c.compute_area() == 12);
77     return 0;
78 }
79 //]
80 
81