2 // Copyright (C) 2008-2019 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/type_traits/has_equal_to.hpp>
14 void swap(T& x, T& y) {
15 constexpr bool b = boost::contract::is_old_value_copyable<T>::value &&
16 boost::has_equal_to<T>::value;
17 boost::contract::old_ptr<T> old_x, old_y;
18 if constexpr(b) { // Contract requires copyable T...
19 old_x = BOOST_CONTRACT_OLDOF(x);
20 old_y = BOOST_CONTRACT_OLDOF(y);
22 boost::contract::check c = boost::contract::function()
24 if constexpr(b) { // ... and T with `==`...
25 BOOST_CONTRACT_ASSERT(x == *old_y);
26 BOOST_CONTRACT_ASSERT(y == *old_x);
31 T t = std::move(x); // ...but body only requires movable T.
37 struct i { // Non-copyable but has operator==.
38 explicit i(int n) : n_(n) {}
40 i(i const&) = delete; // Non-copyable.
41 i& operator=(i const&) = delete;
43 i(i const&& o) : n_(o.n_) {}
44 i& operator=(i const&& o) { n_ = o.n_; return *this; }
46 friend bool operator==(i const& l, i const& r) { // Operator==.
54 struct j { // Copyable but no operator==.
55 explicit j(int n) : n_(n) {}
57 j(j const& o) : n_(o.n_) {} // Copyable.
58 j& operator=(j const& o) { n_ = o.n_; return *this; }
60 j(j const&& o) : n_(o.n_) {}
61 j& operator=(j const&& o) { n_ = o.n_; return *this; }
69 struct k { // Non-copyable and no operator==.
70 explicit k(int n) : n_(n) {}
72 k(k const&) = delete; // Non-copyable.
73 k& operator=(k const&) = delete;
75 k(k const&& o) : n_(o.n_) {}
76 k& operator=(k const&& o) { n_ = o.n_; return *this; }
85 { // Copyable and operator== (so checks postconditions).
92 { // Non-copyable (so does not check postconditions).
99 { // No operator== (so does not check postconditions).
102 // Cannot assert x and y because no operator==.
105 { // Non-copyable and no operator== (so does not check postconditions).
108 // Cannot assert x and y because no operator==.