not_null.hpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // not_null.hpp
  3. // pointer
  4. //
  5. // Created by Sam Jaffe on 9/24/15.
  6. //
  7. //
  8. #pragma once
  9. #include <stdexcept>
  10. #include <memory>
  11. #include "pointer_fwd.hpp"
  12. #include "maybe_null.hpp"
  13. class null_pointer_exception : public std::invalid_argument {
  14. using std::invalid_argument::invalid_argument;
  15. };
  16. template <typename P> class not_null<std::weak_ptr<P>>; // A weak_ptr cannot be a not_null
  17. template <typename T>
  18. class not_null {
  19. public:
  20. using element_type = typename std::pointer_traits<T>::element_type;
  21. using pointer = element_type *;
  22. using reference = element_type &;
  23. explicit not_null(std::nullptr_t) = delete;
  24. explicit not_null(int) = delete;
  25. not_null(T const & p) : _ptr(p) { validate(); }
  26. not_null(T && p) : _ptr(std::move(p)) { validate(); }
  27. not_null(not_null const&) = default;
  28. template <typename Y>
  29. explicit operator maybe_null<Y>() const {
  30. return _ptr;
  31. }
  32. template <typename Y>
  33. explicit operator not_null<Y>() const {
  34. return _ptr;
  35. }
  36. not_null& operator=(not_null const&) = default;
  37. template <typename Y> not_null& operator=(not_null<Y> const&other) {
  38. _ptr = other._ptr;
  39. return *this;
  40. }
  41. explicit operator maybe_null<T>() const;
  42. operator bool() const { return true; }
  43. pointer get() const { return std::addressof(operator*()); }
  44. reference operator*() const { return *_ptr; }
  45. pointer operator->() const { return get(); }
  46. bool operator==(not_null const&rhs) const { return _ptr == rhs._ptr; }
  47. bool operator!=(not_null const&rhs) const { return _ptr != rhs._ptr; }
  48. bool operator<=(not_null const&rhs) const { return _ptr <= rhs._ptr; }
  49. bool operator>=(not_null const&rhs) const { return _ptr >= rhs._ptr; }
  50. bool operator< (not_null const&rhs) const { return _ptr < rhs._ptr; }
  51. bool operator> (not_null const&rhs) const { return _ptr > rhs._ptr; }
  52. private:
  53. void validate() {
  54. if (get() == nullptr) {
  55. throw null_pointer_exception{"not_null<T> cannot be null"};
  56. }
  57. }
  58. T _ptr;
  59. };