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

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

本文关键字:适用于 std 不适用 array 特征 专业化 为什么      更新时间:2023-10-16

我发现有趣的是,这个类型trait不匹配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是一个类模板,是的,但是它的模板参数不是所有类型:

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

在模板元编程领域,任何不是类型的东西都是二等公民。这只是价值观糟糕的一个例子。

如果您编写了自己的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
相关文章: