optional_result.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright (C) 2008-2018 Lorenzo Caminiti
  2. // Distributed under the Boost Software License, Version 1.0 (see accompanying
  3. // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
  4. // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html
  5. #include <boost/contract.hpp>
  6. #include <boost/optional.hpp>
  7. #include <vector>
  8. #include <cassert>
  9. //[optional_result
  10. template<unsigned Index, typename T>
  11. T& get(std::vector<T>& vect) {
  12. boost::optional<T&> result; // Result not initialized here...
  13. boost::contract::check c = boost::contract::function()
  14. .precondition([&] {
  15. BOOST_CONTRACT_ASSERT(Index < vect.size());
  16. })
  17. .postcondition([&] {
  18. BOOST_CONTRACT_ASSERT(*result == vect[Index]);
  19. })
  20. ;
  21. // Function body (executed after preconditions checked).
  22. return *(result = vect[Index]); // ...result initialized here instead.
  23. }
  24. //]
  25. int main() {
  26. std::vector<int> v;
  27. v.push_back(123);
  28. v.push_back(456);
  29. v.push_back(789);
  30. int& x = get<1>(v);
  31. assert(x == 456);
  32. x = -456;
  33. assert(v[1] == -456);
  34. return 0;
  35. }