首页 > 解决方案 > 由模板参数具体化的类型的模板特化

问题描述

首先,我很抱歉问题标题,但很难描述。如果我想专门Resolve针对 的所有实例化,下面这两个中的哪一个是有效语法A
1)

template<uint32_t I> struct A {};

template<typename> struct Resolve;

template<uint32_t I>
struct Resolve<A<I>>
{
    void f() { printf("im here!\n"); }  
};

2)

template<uint32_t I> struct A {};

template<typename> struct Resolve;

template<>
template<uint32_t I>
struct Resolve<A<I>>
{
    void f() { printf("im here!\n"); }  
};

或者是template<>可选的?SO有两个不同的答案:herehere
如有可能,请提供标准报价。

选项 2) 不在 MSVC 上编译,但至少在某些版本的 GCC 上编译。

标签: c++language-lawyer

解决方案


这是对的:

template <uint32_t I>
struct Resolve<A<I>>
{ };

该语法template <>用于引入显式特化(类模板、函数模板等)(参见[temp.spec]/3[temp.expl.spec]/1)。但我们正在尝试进行部分专业化。部分特化仍然需要引入模板参数,而显式特化则不需要。

另一方面,如果我们试图特化显式特化的成员,那么我们将使用template <>. 例如:

template <class T>
struct A {
    template <class T2> struct B { }; // #1
};

template <>         // for A
template <class T2> // for B
struct A<int>::B<T2> { }; // #2

A<char>::B<int> x; // #1
A<int>::B<char> y; // #2

推荐阅读