我正在尝试实现一种结构,该结构在编译时检查给定类型是智能指针还是智能指针的引用。
我重写了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;
由于我的想法已经用完了,您能尝试发现一个错误吗?
答案 0 :(得分:2)
您写的std::enable_if<...>
应该是std::enable_if_t<...>
或std::enable_if<...>::type
。
std::enable_if<...>
是一个独特的类型,永远不会成为void
。因此,如果第二个模板参数默认为void
,则永远不会使用您的部分专业化。
还请注意,您正在忘记自定义删除器。 std::unique_ptr
具有用于自定义删除类型的第二个模板参数,如果未将其指定为默认值,则不会捕获。