c++ - 为什么通用特化特征不适用于 std::array

标签 c++ templates c++11 variadic-templates

<分区>

我觉得有趣的是,这种类型特征与 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;

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

如果您编写了自己的 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

关于c++ - 为什么通用特化特征不适用于 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32187445/

相关文章:

c++ - Kinect SDK 1.8 实例 Winbase.h 报错

python - Django 找不到模板,文件存在并指定了 TEMPLATE_DIR

linux - 使用 CMAKE 编译静态可执行文件

c++ - 无法使用 lambda 函数创建 unordered_set

c++ - 为什么 vector<std::function> 的元素可以绑定(bind)到 C++ 中的不同函数签名?

c++ - 从 unsigned char* 到 char* 的无效转换

c++ - 获取返回的 multimap 迭代器的内容

c++ - 有什么hashmap可以做而map不能做的事吗?

c++ - 如何在 C++ 函数之外限制 `using` 语句的范围?

c++ - 如何在不声明类型的情况下将模板发送到另一个模板?