c++ - 如何使用模板模板参数来专门化类模板?

标签 c++ templates template-specialization partial-specialization

我想在模板模板参数的类型模板参数上专门化一个类模板。是否可以?如果是,语法是什么?

#include <type_traits>

template <typename T>
struct X {};

// primary template
template<template<class> class C>
struct Z : std::false_type {};

// specialization on the template template parameter
template<>
struct Z<X> : std::true_type {}; // OK

// specialization on the type template parameter of the
// template template parameter
template <template<class> class C>
struct Z<C<int>> {}; // ERROR

动机:假设模板模板参数表示集合(例如 std::vectorstd::deque)。我想专门研究 std::vector 上的 Z 但我对 std::vector 的类型模板参数不感兴趣,没关系。另外,我想专注于所有拥有 int 的 Collection 类型。

这个问题与以下问题类似,但它们要么试图专门化函数模板

或者他们试图专注于模板参数

或者主模板中没有模板模板参数

最佳答案

以下代码可以正常编译:

#include <type_traits>

template <typename T>
struct X {};

// primary template, no template template parameter
template<typename T>
struct Z : std::false_type {};

// specialization on the template template parameter with arbitrary T
template<typename T>
struct Z<X<T>> : std::true_type {};

// here's where you need the template template parameter
template <template<class> class C>
struct Z<C<int>> : std::true_type {};

int main()
{
    static_assert(!Z<Z<double>>::value, "" );
    static_assert( Z<Z<int   >>::value, "" );
    static_assert( Z<X<double>>::value, "" );
//  static_assert( Z<X<int   >>::value, "" ); // error: ambiguous 
                                              // partial specialization
}

在您的代码中,您为 Z 提供了模板模板参数,即使这应该仅针对特化而完成。这就是您的代码无法编译的原因。

关于c++ - 如何使用模板模板参数来专门化类模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34426292/

相关文章:

C++模板类的函数

具有特定接口(interface)的类型的 C++ 模板特化

C++ 专门化单一成员函数

c++ - 在 C++ 中将内存分配给 char*

c++ - 模板特化与默认值

c++ - Windows Qt 二进制安装程序是否支持开箱即用的 DBus?

未在此范围内声明的 C++ 模板成员函数

c++ - Container::value_type 的模板特化

c++ - 用 g++ 编译 C++11

C++ rand() 不断返回相同的数字