问题描述
为什么我可以这样做:
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给出以下错误:
For the second case, GCC gives the following error:
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> >'
编辑:
在解释为什么不允许第二个示例的原因时,还请考虑将成员函数也设置为模板不会影响哪个示例有效,哪个无效.也就是说,这仍然有效:
When explaining why the second example is not allowed, please also consider that making the member function also a template has no effect on which example works and which does not. That is, this still works:
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
仍然存在),并且可以正常工作.
So the reason cannot be that function templates can only be fully specialized, because the third example is not a full specialization (the template parameter U
is still there), and yet it works.
推荐答案
功能模板只能完全地专门化,而不能部分地专门化.
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.
关于您的以下内容可以从14.7.3/1开始明确(即完全)进行专门化:
As for your edit: The following things can be explicitly (i.e. completely) specialized, from 14.7.3/1:
—功能模板
—类模板
— 课程模板的成员功能
-类模板的静态数据成员
— static data member of a class template
-类模板的成员类
—类模板的成员枚举
-类或类模板的成员类模板
— member class template of a class or class template
— 类的成员函数模板或类模板
可以由template<>;
我已经强调了适用于您的情况的两个陈述.缺少任何其他明确规定,这些实体可能不能部分地专门化.
I've emphasized the two statements that apply to your case. Absent any other explicit provisions, those entities can not be specialized partially.
这篇关于成员函数的部分专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!