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/optional.hpp> 9 #include <vector> 10 #include <cassert> 11 12 //[optional_result 13 template<unsigned Index, typename T> get(std::vector<T> & vect)14T& get(std::vector<T>& vect) { 15 boost::optional<T&> result; // Result not initialized here... 16 boost::contract::check c = boost::contract::function() 17 .precondition([&] { 18 BOOST_CONTRACT_ASSERT(Index < vect.size()); 19 }) 20 .postcondition([&] { 21 BOOST_CONTRACT_ASSERT(*result == vect[Index]); 22 }) 23 ; 24 25 // Function body (executed after preconditions checked). 26 return *(result = vect[Index]); // ...result initialized here instead. 27 } 28 //] 29 main()30int main() { 31 std::vector<int> v; 32 v.push_back(123); 33 v.push_back(456); 34 v.push_back(789); 35 int& x = get<1>(v); 36 assert(x == 456); 37 x = -456; 38 assert(v[1] == -456); 39 return 0; 40 } 41 42