Skip to content

Commit

Permalink
Use std::pointer_traits::to_address if possible
Browse files Browse the repository at this point in the history
  • Loading branch information
lackhole committed Aug 26, 2024
1 parent cb7b88b commit c1b9d0d
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions include/preview/__memory/to_address.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,35 @@
#include <type_traits>

#include "preview/__memory/pointer_traits.h"
#include "preview/__type_traits/detail/tag.h"
#include "preview/__type_traits/has_operator_arrow.h"
#include "preview/__type_traits/void_t.h"

namespace preview {
namespace detail {

template<typename T, typename = void>
template<typename T, template<typename> class Traits, typename = void>
struct has_to_address : std::false_type {};

template<typename T, template<typename> class Traits>
struct has_to_address<T, Traits, void_t<decltype(Traits<T>::to_address(std::declval<const T&>()))>> : std::true_type {};

template<typename T>
struct has_to_address<T, void_t<decltype(pointer_traits<T>::to_address(std::declval<const T&>()))>> : std::true_type {};
using to_address_tag = conditional_tag<
has_to_address<T, std::pointer_traits>,
has_to_address<T, pointer_traits>
>;

template<typename T>
constexpr auto to_address_fancy(const T& p, std::true_type /* has_to_address */ ) noexcept {
return preview::pointer_traits<T>::to_address(p);
constexpr auto to_address_fancy(const T& p, preview::detail::tag_1 /* std::pointer_traits<T>::to_address */ ) noexcept {
return std::pointer_traits<T>::to_address(p);
}
template<typename T>
constexpr auto to_address_fancy(const T& p, preview::detail::tag_2 /* pointer_traits<T>::to_address */ ) noexcept {
return pointer_traits<T>::to_address(p);
}
template<typename T>
constexpr auto to_address_fancy(const T& p, std::false_type /* has_to_address */ ) noexcept;
constexpr auto to_address_fancy(const T& p, preview::detail::tag_else /* no to_address */ ) noexcept;

} // namespace detail

Expand All @@ -38,13 +49,13 @@ constexpr T* to_address(T* p) noexcept {

template<class T>
constexpr auto to_address(const T& p) noexcept {
return detail::to_address_fancy(p, detail::has_to_address<T>{});
return detail::to_address_fancy(p, detail::to_address_tag<T>{});
}

namespace detail {

template<typename T>
constexpr auto to_address_fancy(const T& p, std::false_type /* has_to_address */ ) noexcept {
constexpr auto to_address_fancy(const T& p, preview::detail::tag_else /* no to_address */ ) noexcept {
return preview::to_address(p.operator->());
}

Expand Down

0 comments on commit c1b9d0d

Please sign in to comment.