private_protected.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 <limits>
  7. #include <cassert>
  8. //[private_protected
  9. class counter {
  10. protected: // Protected functions use `function()` (like non-members).
  11. void set(int n) {
  12. boost::contract::check c = boost::contract::function()
  13. .precondition([&] {
  14. BOOST_CONTRACT_ASSERT(n <= 0);
  15. })
  16. .postcondition([&] {
  17. BOOST_CONTRACT_ASSERT(get() == n);
  18. })
  19. ;
  20. n_ = n;
  21. }
  22. private: // Private functions use `function()` (like non-members).
  23. void dec() {
  24. boost::contract::old_ptr<int> old_get = BOOST_CONTRACT_OLDOF(get());
  25. boost::contract::check c = boost::contract::function()
  26. .precondition([&] {
  27. BOOST_CONTRACT_ASSERT(
  28. get() + 1 >= std::numeric_limits<int>::min());
  29. })
  30. .postcondition([&] {
  31. BOOST_CONTRACT_ASSERT(get() == *old_get - 1);
  32. })
  33. ;
  34. set(get() - 1);
  35. }
  36. int n_;
  37. /* ... */
  38. //]
  39. public:
  40. int get() const {
  41. int result;
  42. boost::contract::check c = boost::contract::public_function(this)
  43. .postcondition([&] {
  44. BOOST_CONTRACT_ASSERT(result <= 0);
  45. BOOST_CONTRACT_ASSERT(result == n_);
  46. })
  47. ;
  48. return result = n_;
  49. }
  50. counter() : n_(0) {} // Should contract constructor and destructor too.
  51. void invariant() const {
  52. BOOST_CONTRACT_ASSERT(get() <= 0);
  53. }
  54. friend int main();
  55. };
  56. int main() {
  57. counter cnt;
  58. assert(cnt.get() == 0);
  59. cnt.dec();
  60. assert(cnt.get() == -1);
  61. return 0;
  62. }