| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- //
- // copy_ptr.hpp
- // pointers
- //
- // Created by Sam Jaffe on 12/6/16.
- //
- #pragma once
- #include <memory>
- #include "pointer_fwd.hpp"
- #include "ptr_compare.hpp"
- namespace detail {
- template <typename T>
- T * copy_ptr_from_ptr(T const * ptr) {
- return ptr ? new T(*ptr) : nullptr;
- }
-
- template <typename T>
- using clone_func = T* (T::*)() const;
-
- template <typename T, clone_func<T> Clone>
- T * clone_ptr_from_ptr(T const * ptr) {
- return ptr ? (ptr->*Clone)() : nullptr;
- }
- }
- template <typename T, T*(*Copy)(T const *) = &detail::copy_ptr_from_ptr<T> >
- class copy_ptr {
- public:
- using element_type = T;
- using pointer = element_type *;
- using reference = element_type &;
-
- copy_ptr() : _ptr(nullptr) {}
- copy_ptr(T * const & p) = delete;
- copy_ptr(T * && p) : _ptr(std::move(p)) {}
- copy_ptr(copy_ptr const & other) : _ptr(Copy(other._ptr)) {}
- copy_ptr(copy_ptr &&) = default;
-
- template <typename Y>
- explicit operator copy_ptr<Y>() const {
- return Copy(_ptr);
- }
-
- ~copy_ptr() { delete _ptr; }
-
- copy_ptr & operator=(copy_ptr const & other) {
- swap(copy_ptr{other});
- return *this;
- }
- copy_ptr & operator=(copy_ptr &&) = default;
-
- operator bool() const {
- return static_cast<bool>(_ptr);
- }
-
- pointer get() const { return _ptr; }
- pointer operator->() const { return get(); }
- reference operator*() const { return *get(); }
- private:
- T * _ptr;
- };
- template <typename T, detail::clone_func<T> Clone>
- using clone_ptr = copy_ptr<T, &detail::clone_ptr_from_ptr<T, Clone>>;
- POINTER_TEMPLATE_COMPARE_FULL( copy_ptr,
- (typename T1, T1*(*C1)(T1*)), (T1, C1),
- (typename T2, T2*(*C2)(T2*)), (T2, C2))
|