friend.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 <string>
  7. #include <cassert>
  8. //[friend_byte
  9. class buffer;
  10. class byte {
  11. friend bool operator==(buffer const& left, byte const& right);
  12. private:
  13. char value_;
  14. /* ... */
  15. //]
  16. public:
  17. // Could program invariants and contracts for following too.
  18. explicit byte(char value) : value_(value) {}
  19. bool empty() const { return value_ == '\0'; }
  20. };
  21. //[friend_buffer
  22. class buffer {
  23. // Friend functions are not member functions...
  24. friend bool operator==(buffer const& left, byte const& right) {
  25. // ...so check contracts via `function` (which won't check invariants).
  26. boost::contract::check c = boost::contract::function()
  27. .precondition([&] {
  28. BOOST_CONTRACT_ASSERT(!left.empty());
  29. BOOST_CONTRACT_ASSERT(!right.empty());
  30. })
  31. ;
  32. for(char const* x = left.values_.c_str(); *x != '\0'; ++x) {
  33. if(*x != right.value_) return false;
  34. }
  35. return true;
  36. }
  37. private:
  38. std::string values_;
  39. /* ... */
  40. //]
  41. public:
  42. // Could program invariants and contracts for following too.
  43. explicit buffer(std::string const& values) : values_(values) {}
  44. bool empty() const { return values_ == ""; }
  45. };
  46. int main() {
  47. buffer p("aaa");
  48. byte a('a');
  49. assert(p == a);
  50. buffer q("aba");
  51. assert(!(q == a)); // No operator!=.
  52. return 0;
  53. }