如何检查类型是智能指针还是对智能指针的引用
How to check if a type is a smart pointer or a reference to a smart pointer
我正在尝试实现一种在编译时检查给定类型是智能指针还是对智能指针的引用的结构。
我重写了 this 解决方案(不适用于参考):
template<typename T, typename Enable = void>
struct IsSmartPointer : std::false_type {
};
template<typename T>
struct IsSmartPointer<T,
typename std::enable_if<
std::is_same<
typename std::decay_t<T>, std::unique_ptr<typename std::decay_t<T>::element_type>
>::value
>
> : std::true_type {
};
template<typename T>
struct IsSmartPointer<T,
typename std::enable_if<
std::is_same<
typename std::decay_t<T>, std::shared_ptr<typename std::decay_t<T>::element_type>
>::value
>
> : std::true_type {
};
template<typename T>
struct IsSmartPointer<T,
typename std::enable_if<
std::is_same<
typename std::decay_t<T>, std::weak_ptr<typename std::decay_t<T>::element_type>
>::value
>
> : std::true_type {
};
我觉得这个实现非常接近正确的解决方案。然而,下面的代码打印出零:
std::cout << IsSmartPointer<int>::value << '\n'
<< IsSmartPointer<const std::shared_ptr<int> &>::value << '\n'
<< IsSmartPointer<std::shared_ptr<int> &>::value << '\n'
<< IsSmartPointer<const std::shared_ptr<int>>::value << '\n'
<< IsSmartPointer<std::shared_ptr<int>>::value
<< std::endl;
我运行没主意了,你能不能帮我找出错误?
你写了 std::enable_if<...>
,而它应该是 std::enable_if_t<...>
或 std::enable_if<...>::type
。
std::enable_if<...>
是一种独特的类型,永远不会是 void
。因此,如果第二个模板参数默认为 void
.
,则永远不会使用您的偏特化
另请注意,您忘记了自定义删除器。 std::unique_ptr
有第二个用于自定义删除器类型的模板参数,如果未将其指定为默认值,您将无法捕获。
我正在尝试实现一种在编译时检查给定类型是智能指针还是对智能指针的引用的结构。
我重写了 this 解决方案(不适用于参考):
template<typename T, typename Enable = void>
struct IsSmartPointer : std::false_type {
};
template<typename T>
struct IsSmartPointer<T,
typename std::enable_if<
std::is_same<
typename std::decay_t<T>, std::unique_ptr<typename std::decay_t<T>::element_type>
>::value
>
> : std::true_type {
};
template<typename T>
struct IsSmartPointer<T,
typename std::enable_if<
std::is_same<
typename std::decay_t<T>, std::shared_ptr<typename std::decay_t<T>::element_type>
>::value
>
> : std::true_type {
};
template<typename T>
struct IsSmartPointer<T,
typename std::enable_if<
std::is_same<
typename std::decay_t<T>, std::weak_ptr<typename std::decay_t<T>::element_type>
>::value
>
> : std::true_type {
};
我觉得这个实现非常接近正确的解决方案。然而,下面的代码打印出零:
std::cout << IsSmartPointer<int>::value << '\n'
<< IsSmartPointer<const std::shared_ptr<int> &>::value << '\n'
<< IsSmartPointer<std::shared_ptr<int> &>::value << '\n'
<< IsSmartPointer<const std::shared_ptr<int>>::value << '\n'
<< IsSmartPointer<std::shared_ptr<int>>::value
<< std::endl;
我运行没主意了,你能不能帮我找出错误?
你写了 std::enable_if<...>
,而它应该是 std::enable_if_t<...>
或 std::enable_if<...>::type
。
std::enable_if<...>
是一种独特的类型,永远不会是 void
。因此,如果第二个模板参数默认为 void
.
另请注意,您忘记了自定义删除器。 std::unique_ptr
有第二个用于自定义删除器类型的模板参数,如果未将其指定为默认值,您将无法捕获。