condition_if.cpp 1.5 KB

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