| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- //
- // 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>
- using clone_func = T* (T::*)() const;
-
- template <typename T, typename = void>
- class value_ptr_copy;
-
- template <typename T>
- struct value_ptr_copy<T, typename std::enable_if<!std::is_polymorphic<T>::value>::type> {
- T * Copy( T * ptr ) const { return ptr ? new T(*ptr) : nullptr; }
- };
- #define POLYMORPHIC_VALUE_PTR_GROUP_FROM_CLONE_FUNCTION( fclone ) \
- template <typename T> \
- struct value_ptr_copy<T, typename std::enable_if<std::is_polymorphic<T>::value \
- && std::is_same<clone_func<T>, decltype(&T::fclone)>::value>::type> { \
- T * Copy( T * ptr ) const { return ptr ? ptr->fclone() : nullptr; } \
- }
- POLYMORPHIC_VALUE_PTR_GROUP_FROM_CLONE_FUNCTION( Clone );
- POLYMORPHIC_VALUE_PTR_GROUP_FROM_CLONE_FUNCTION( clone );
- POLYMORPHIC_VALUE_PTR_GROUP_FROM_CLONE_FUNCTION( Copy );
- POLYMORPHIC_VALUE_PTR_GROUP_FROM_CLONE_FUNCTION( copy );
- }
- template <typename T>
- class value_ptr : private detail::value_ptr_copy<T> {
- public:
- using element_type = T;
- using pointer = element_type *;
- using reference = element_type &;
-
- value_ptr() noexcept : _ptr(nullptr) {}
- value_ptr(T * const & p) = delete;
- value_ptr(T * && p) noexcept(std::is_nothrow_move_constructible<T>::value) : _ptr(std::move(p)) {}
- value_ptr(value_ptr const & other) : _ptr(detail::value_ptr_copy<T>::Copy(other._ptr)) {}
- value_ptr(value_ptr && other) noexcept(noexcept(std::swap(_ptr, other._ptr))) : _ptr(nullptr) { std::swap(_ptr, other._ptr); }
- static value_ptr copy_of(T * const & p) {
- return detail::value_ptr_copy<T>().Copy(p);
- }
-
- template <typename Y>
- explicit operator value_ptr<Y>() const {
- return Copy(_ptr);
- }
-
- ~value_ptr() { delete _ptr; }
-
- value_ptr & operator=(value_ptr const & other) noexcept(noexcept(swap(_ptr, other._ptr))) {
- swap(_ptr, value_ptr{other}._ptr);
- return *this;
- }
- value_ptr & operator=(value_ptr && other) noexcept(noexcept(swap(_ptr, other._ptr))) {
- swap(_ptr, other._ptr);
- return *this;
- }
-
- operator bool() const noexcept {
- return static_cast<bool>(_ptr);
- }
-
- pointer get() const noexcept { return _ptr; }
- pointer operator->() const noexcept { return get(); }
- reference operator*() const noexcept { return *get(); }
- private:
- T * _ptr;
- };
- POINTER_TEMPLATE_COMPARE( value_ptr )
|