为什么通用专业化特征不适用于 std::array

Why doesn't the generic specialization trait apply to std::array

我发现有趣的是这个类型特征不匹配 std::array(它给出了一个编译错误)但是它适用于 unordered_map。这是为什么?

#include <iostream>
#include <unordered_map>
#include <array>

template <typename T, template <typename...> class Ref>
struct is_specialization : std::false_type {
};

template <template <typename...> class Ref, typename... Args>
struct is_specialization<Ref<Args...>, Ref> : std::true_type {
};

int main()
{
    using T = std::unordered_map<int, int>;
    using C = std::array<int, 2>;
    auto value = is_specialization<T, std::unordered_map>::value;
    std::cout << "Is type of unorderd map specialization? : " << std::boolalpha << value << std::endl;

    auto secondValue = is_specialization<C , std::array>::value;
    std::cout << "Is type of array specialization? : " << std::boolalpha << secondValue << std::endl;
}

您的主模板有两个参数:一个类型参数和一个模板模板参数,其模板参数均为类型:

template <typename T, template <typename...> class Ref>
struct is_specialization;

std::array 是一个 class 模板,是的,但它的模板参数并非所有类型:

template< 
    class T, 
    std::size_t N  // <== not a type
> struct array;

任何不是类型的东西都是模板元编程领域的第二个 class 公民。这只是为什么价值观很糟糕的一个例子。

如果您编写了自己的 array 包装器并采用了两种类型:

template <typename T, typename N>
struct my_array : std::array<T, N::value> { };

然后你就可以像你期望的那样使用你的特质了:

using C = my_array<int, std::integral_constant<int, 2>>;
auto secondValue = is_specialization<C , my_array>::value; // true