5

可能重复:
部分模板专业化的“不完整类型的无效使用”错误

为什么我可以这样做:

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

template <>
void A<int>::foo(int)
{
}

但不是这个:

template <typename> struct C {};

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

template <typename T>
void A<C<T> >::foo(int)
{
}

对于第二种情况,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> >'

编辑

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

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

template <>
template <typename U>
void A<int>::foo(U)
{
}

但这不会:

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)
{
}

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

4

1 回答 1

8

Function templates can only be specialised completely, not partially.

You're using the fact that member functions of class templates are themselves function templates, so this rule still applies.


As for your edit: The following things can be explicitly (i.e. completely) specialized, from 14.7.3/1:

An explicit specialization of any of the following:

— function template

— class template

member function of a class template

— static data member of a class template

— member class of a class template

— member enumeration of a class template

— member class template of a class or class template

member function template of a class or class template

can be declared by a declaration introduced by template<>;

I've emphasized the two statements that apply to your case. Absent any other explicit provisions, those entities can not be specialized partially.

于 2012-09-09T01:19:32.527 回答