测试 std::pointer_traits 是否适用于我的类型

Testing if std::pointer_traits can work with my type

如何在编译时检查任意类型是否可以与 std::pointer_traits 一起使用?我曾希望一个简单的 SFINAE 解决方案可能有效:

template <typename T, typename = void>
struct pointer_traits_ready : std::false_type {};

template <typename T>
struct pointer_traits_ready<
         T,
         std::void_t<typename std::pointer_traits<T>::element_type>
       > : std::true_type {};

static_assert(!pointer_traits_ready<int>::value,"");

...但这会从标准库 (ptr_traits.h) 中调用静态断言。显然 std::is_pointer 不支持智能指针。

你不能。来自 [pointer.traits.types]:

using element_type = see below ;

Type: Ptr::element_type if the qualified-id Ptr::element_type is valid and denotes a type (14.8.2); otherwise, T if Ptr is a class template instantiation of the form SomePointer<T, Args>, where Args is zero or more type arguments; otherwise, the specialization is ill-formed.

为了对 SFINAE 友好,我们需要 pointer_traits<Foo> 简单地缺少一个名为 element_type 的类型别名。问题是,element_type 被指定为格式错误 - 并非不存在。所以你根本不能使用 pointer_traits 作为检测器来判断某物是否可以用作指针类型。

即使您自己编写的类型是该规范的 SFINAE 友好版本,您也无法捕获 pointer_traits 用户自己类型的特化。悲伤的熊猫。