模板类 - 成员函数专门化 [英] template class - member function specialization

查看:109
本文介绍了模板类 - 成员函数专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是示例代码:

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;
}

上述代码适用于和不使用 template< >之前的成员函数专门化。为什么?
在这种情况下会有什么区别?

The above code works with and without template<> before a member function specialization. Why ? What difference does it make in such case ?

Edit1:
我以这种方式使用该模板(VS 2012编译器):

I use that template this way (VS 2012 compiler):

A<int> a1(1);
cout<<a1.getX()<<endl;
A<long> a2(1);
cout<<a2.getX()<<endl;


推荐答案

不合规,

FWIW, GCC 4.8拒绝您的代码,而不使用模板<>

FWIW, GCC 4.8 rejects your code without the template <>.

支持这一点的扩展;我可以确认MSVS 2012接受代码。我被告知,MSVS 2013年11月CTP也吃了没有投诉。公平地说,Visual Studio对模板规范总是相当宽松。

Your compiler is either buggy or has an extension to support this; I can confirm that MSVS 2012 accepts the code. I'm told that MSVS 2013 November CTP also eats it up without complaint. To be fair, Visual Studio was always fairly lenient about template specifications.


[C ++ 11:14.7 / 3]: 可以为一个函数模板,一个类模板,类模板的成员或成员模板声明一个显式特化。 template<> [..]

[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. An explicit specialization declaration is introduced by template<>. [..]

此规则的唯一例外是:


[C ++ 11:14.7.3 / 5]: [..] 明确专门类模板的成员是
作为正常类的成员,而不使用模板<> 语法。 [..]

[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 the template<> syntax. [..]

…但不适用于此。

… but that does not apply here.

这篇关于模板类 - 成员函数专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆