问题描述
template<typename T>
class CConstraint
{
public:
CConstraint()
{
}
virtual ~CConstraint()
{
}
template <typename TL>
void Verify(int position, int constraints[])
{
}
template <>
void Verify<int>(int, int[])
{
}
};
在 g++ 下编译会出现以下错误:
Compiling this under g++ gives the following error:
在非命名空间范围class CConstraint"中的显式特化
Explicit specialization in non-namespace scope 'class CConstraint'
在 VC 中,它编译得很好.任何人都可以告诉我解决方法吗?
In VC, it compiles fine. Can anyone please let me know the workaround?
推荐答案
VC++ 在这种情况下是不兼容的 - 显式专业化必须在命名空间范围内.C++03,§14.7.3/2:
VC++ is non-compliant in this case - explicit specializations have to be at namespace scope. C++03, §14.7.3/2:
应在模板为其成员的命名空间中声明显式特化,或者对于成员模板,应在封闭类或封闭类模板为其成员的命名空间中声明.
类模板的成员函数、成员类或静态数据成员的显式特化应在类模板所属的命名空间中声明.
An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member.
An explicit specialization of a member function, member class or static data member of a class template shall be declared in the namespace of which the class template is a member.
此外,由于 C++03 §14.7.3/3,您无法在不显式专门化包含类的情况下专门化成员函数,因此一种解决方案是让Verify()
转发到一个可能专门的免费函数:
Additionally you have the problem that you can't specialize member functions without explicitly specializing the containing class due to C++03, §14.7.3/3, so one solution would be to let Verify()
forward to a, possibly specialized, free function:
namespace detail {
template <typename TL> void Verify (int, int[]) {}
template <> void Verify<int>(int, int[]) {}
}
template<typename T> class CConstraint {
// ...
template <typename TL> void Verify(int position, int constraints[]) {
detail::Verify<TL>(position, constraints);
}
};
这篇关于非命名空间范围内的显式特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!