lambda.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 <vector>
  7. #include <algorithm>
  8. #include <limits>
  9. int main() {
  10. std::vector<int> v;
  11. v.push_back(1);
  12. v.push_back(2);
  13. v.push_back(3);
  14. //[lambda
  15. int total = 0;
  16. std::for_each(v.cbegin(), v.cend(),
  17. // Contract for a lambda function.
  18. [&total] (int const x) {
  19. boost::contract::old_ptr<int> old_total =
  20. BOOST_CONTRACT_OLDOF(total);
  21. boost::contract::check c = boost::contract::function()
  22. .precondition([&] {
  23. BOOST_CONTRACT_ASSERT(
  24. total < std::numeric_limits<int>::max() - x);
  25. })
  26. .postcondition([&] {
  27. BOOST_CONTRACT_ASSERT(total == *old_total + x);
  28. })
  29. ;
  30. total += x; // Lambda function body.
  31. }
  32. );
  33. //]
  34. assert(total == 6);
  35. return 0;
  36. }