成员函数的部分特化

HC4*_*ica 5 c++ templates partial-specialization template-specialization

可能重复:
部分模板特化的"无效使用不完整类型"错误

为什么我能做到这一点:

template <typename T>
struct A
{
    void foo(int);
};

template <>
void A<int>::foo(int)
{
}
Run Code Online (Sandbox Code Playgroud)

但不是这个:

template <typename> struct C {};

template <typename T>
struct A
{
    void foo(int);
};

template <typename T>
void A<C<T> >::foo(int)
{
}
Run Code Online (Sandbox Code Playgroud)

对于第二种情况,GCC给出以下错误:

test.cpp:10:23: error: invalid use of incomplete type 'struct A<C<T> >'
test.cpp:4:8: error: declaration of 'struct A<C<T> >'
Run Code Online (Sandbox Code Playgroud)

编辑:

在解释为什么不允许第二个例子时,请同时考虑使成员函数也是一个模板对哪个例子有效,哪个没有影响.也就是说,这仍然有效:

template <typename T>
struct A
{
    template <typename U>
    void foo(U);
};

template <>
template <typename U>
void A<int>::foo(U)
{
}
Run Code Online (Sandbox Code Playgroud)

但这不是:

template <typename> struct C {};

template <typename T>
struct A
{
    template <typename U>
    void foo(U);
};

template <typename T>
template <typename U>
void A<C<T> >::foo(U)
{
}
Run Code Online (Sandbox Code Playgroud)

所以原因不能是函数模板只能完全专门化,因为第三个例子不是完全特化(模板参数U仍然存在),但它仍然有效.

Ker*_* SB 7

功能模板只能完全专用,而不是部分专用.

您正在使用类模板的成员函数本身就是函数模板的事实,因此该规则仍然适用.


至于你的编辑:从14.7.3/1可以明确(即完全)专门化以下事项:

以下任何一种明确的专业化:

- 功能模板

- 课堂模板

- 类模板的成员函数

- 类模板的静态数据成员

- 类模板的成员类

- 类模板的成员枚举

- 类或类模板的成员类模板

- 类或类模板的成员函数模板

可以通过引入的声明声明 template<>;

我已经强调了适用于您案件的两个陈述.如果没有任何其他明确规定,这些实体不能部分专门化.