summaryrefslogtreecommitdiffstats
path: root/src/boost/libs/contract/example/features/friend.cpp
blob: 215cfa6dd47a142c172e2ead742e3ac767345ce6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Copyright (C) 2008-2018 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0 (see accompanying
// file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
// See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html

#include <boost/contract.hpp>
#include <string>
#include <cassert>

//[friend_byte
class buffer;

class byte {
    friend bool operator==(buffer const& left, byte const& right);
    
private:
    char value_;

    /* ... */
//]

public:
    // Could program invariants and contracts for following too.
    explicit byte(char value) : value_(value) {}
    bool empty() const { return value_ == '\0'; }
};

//[friend_buffer
class buffer {
    // Friend functions are not member functions...
    friend bool operator==(buffer const& left, byte const& right) {
        // ...so check contracts via `function` (which won't check invariants).
        boost::contract::check c = boost::contract::function()
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(!left.empty());
                BOOST_CONTRACT_ASSERT(!right.empty());
            })
        ;
        
        for(char const* x = left.values_.c_str(); *x != '\0'; ++x) {
            if(*x != right.value_) return false;
        }
        return true;
    }

private:
    std::string values_;

    /* ... */
//]

public:
    // Could program invariants and contracts for following too.
    explicit buffer(std::string const& values) : values_(values) {}
    bool empty() const { return values_ == ""; }
};

int main() {
    buffer p("aaa");
    byte a('a');
    assert(p == a);

    buffer q("aba");
    assert(!(q == a)); // No operator!=.
    
    return 0;
}