• 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 #include <boost/contract.hpp>
8 #include <string>
9 #include <cassert>
10 
11 //[friend_byte
12 class buffer;
13 
14 class byte {
15     friend bool operator==(buffer const& left, byte const& right);
16 
17 private:
18     char value_;
19 
20     /* ... */
21 //]
22 
23 public:
24     // Could program invariants and contracts for following too.
byte(char value)25     explicit byte(char value) : value_(value) {}
empty() const26     bool empty() const { return value_ == '\0'; }
27 };
28 
29 //[friend_buffer
30 class buffer {
31     // Friend functions are not member functions...
operator ==(buffer const & left,byte const & right)32     friend bool operator==(buffer const& left, byte const& right) {
33         // ...so check contracts via `function` (which won't check invariants).
34         boost::contract::check c = boost::contract::function()
35             .precondition([&] {
36                 BOOST_CONTRACT_ASSERT(!left.empty());
37                 BOOST_CONTRACT_ASSERT(!right.empty());
38             })
39         ;
40 
41         for(char const* x = left.values_.c_str(); *x != '\0'; ++x) {
42             if(*x != right.value_) return false;
43         }
44         return true;
45     }
46 
47 private:
48     std::string values_;
49 
50     /* ... */
51 //]
52 
53 public:
54     // Could program invariants and contracts for following too.
buffer(std::string const & values)55     explicit buffer(std::string const& values) : values_(values) {}
empty() const56     bool empty() const { return values_ == ""; }
57 };
58 
main()59 int main() {
60     buffer p("aaa");
61     byte a('a');
62     assert(p == a);
63 
64     buffer q("aba");
65     assert(!(q == a)); // No operator!=.
66 
67     return 0;
68 }
69 
70