[英]template class - member function specialization
Here is an example code:这是一个示例代码:
template<class T>
class A
{
public:
A(T t): x(t){}
T getX();
private:
T x;
};
template<class T>
T A<T>::getX()
{
return x;
}
// member function specialization
template<> // works with and without template<>
long A<long>::getX()
{
return 1000L;
}
The above code works with and without template<> before a member function specialization.上面的代码在成员函数特化之前使用和不使用模板<> 。 Why ?为什么? What difference does it make in such case ?在这种情况下有什么区别?
Edit1: I use that template this way (VS 2012 compiler): Edit1:我以这种方式使用该模板(VS 2012 编译器):
A<int> a1(1);
cout<<a1.getX()<<endl;
A<long> a2(1);
cout<<a2.getX()<<endl;
Not compliantly, it doesn't.不合规,不合规。
FWIW, GCC 4.8 rejects your code without the template <>
. FWIW, GCC 4.8 拒绝没有template <>
代码。
Your compiler is either buggy or has an extension to support this;你的编译器要么有问题,要么有扩展支持; I can confirm that MSVS 2012 accepts the code.我可以确认 MSVS 2012 接受代码。 I'm told that MSVS 2013 November CTP also eats it up without complaint.我听说 MSVS 2013 年 11 月 CTP 也毫无怨言地吃掉了它。 To be fair, Visual Studio was always fairly lenient about template specifications.公平地说,Visual Studio 对模板规范总是相当宽容。
[C++11: 14.7/3]:
An explicit specialization may be declared for a function template, a class template, a member of a class template or a member template.[C++11: 14.7/3]:
可以为函数模板、类模板、类模板的成员或成员模板声明显式特化。 An explicit specialization declaration is introduced bytemplate<>
.template<>
引入了显式特化声明。 [..] [..]
The only exception to this rule is:此规则的唯一例外是:
[C++11: 14.7.3/5]:
[..] Members of an explicitly specialized class template are defined in the same manner as members of normal classes, and not using thetemplate<>
syntax.[C++11: 14.7.3/5]:
[..]显式专用类模板的成员以与普通类成员相同的方式定义,并且不使用template<>
语法。 [..] [..]
… but that does not apply here. ……但这不适用于这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.