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 <boost/type_traits/has_equal_to.hpp> 9 #include <boost/bind.hpp> 10 #include <vector> 11 #include <functional> 12 #include <cassert> 13 14 //[condition_if 15 template<typename T> 16 class vector { 17 public: push_back(T const & value)18 void push_back(T const& value) { 19 boost::contract::check c = boost::contract::public_function(this) 20 .postcondition([&] { 21 // Instead of `ASSERT(back() == value)` for T without `==`. 22 BOOST_CONTRACT_ASSERT( 23 boost::contract::condition_if<boost::has_equal_to<T> >( 24 boost::bind(std::equal_to<T>(), 25 boost::cref(back()), 26 boost::cref(value) 27 ) 28 ) 29 ); 30 }) 31 ; 32 33 vect_.push_back(value); 34 } 35 36 /* ... */ 37 //] 38 back() const39 T const& back() const { return vect_.back(); } 40 41 private: 42 std::vector<T> vect_; 43 }; 44 main()45int main() { 46 vector<int> v; 47 v.push_back(1); // Type `int` has `==` so check postcondition. 48 assert(v.back() == 1); 49 50 struct i { int value; } j; 51 j.value = 10; 52 vector<i> w; 53 w.push_back(j); // Type `i` has no `==` so skip postcondition. 54 assert(j.value == 10); 55 56 return 0; 57 } 58 59