如何检查类型是智能指针还是智能指针的引用

问题描述 投票:1回答:1

我正在尝试实现一种结构,该结构在编译时检查给定类型是智能指针还是智能指针的引用。

我重写了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;

您是否可以因为我用尽了主意而尝试发现错误?

c++ c++11 templates sfinae typechecking
1个回答
0
投票

您写了std::enable_if<...>,应该是std::enable_if_t<...>std::enable_if<...>::type

std::enable_if<...>是一种绝对不会成为void的独特类型。因此,如果第二个模板参数默认为void,则将永远不会使用您的部分专业化知识。

© www.soinside.com 2019 - 2024. All rights reserved.