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

2番目のケースでは、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> >'

編集

2番目の例が許可されない理由を説明するときは、メンバー関数をテンプレートとして作成しても、どの例が機能し、どの例が機能しないかには影響しないことも考慮してください。つまり、これは引き続き機能します。

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したがって、3番目の例は完全な特殊化ではなく(テンプレートパラメータはまだ存在します)、それでも機能するため、関数テンプレートは完全に特殊化することしかできないという理由はありません。

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 に答える