Tib*_*ibi 5 c++ syntax templates template-specialization
我有一个类模板,我们称之为A
,它具有一个成员函数abc()
:
template <typename T>
class A{
public:
T value;
void abc();
};
Run Code Online (Sandbox Code Playgroud)
我可以abc()
使用以下语法在类声明之外实现成员函数:
template <typename T>
void A<T>::abc()
{
value++;
}
Run Code Online (Sandbox Code Playgroud)
我想做的就是为这个类创建模板专门化int
。
template <>
class A<int>{
public:
int value;
void abc();
};
Run Code Online (Sandbox Code Playgroud)
问题是:abc()
为特殊类实现的正确语法是什么?
我尝试使用以下语法:
template <>
void A<int>::abc()
{
value += 2;
}
Run Code Online (Sandbox Code Playgroud)
但是,这不能编译。
void A<int>::abc()\n{\n value += 2;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n因为A<int>
是explicit specialisation
的A<T>
.
http://liveworkspace.org/code/982c66b2cbfdb56305180914266831d1
\n\nn3337 14.7.3/5\n
\n\n显式专用类模板的成员\n以与普通类成员相同的方式定义,并且不使用 template<> 语法。
\n\n[ 例子:
\n\nRun Code Online (Sandbox Code Playgroud)\n\ntemplate<class T> struct A {\nstruct B { };\ntemplate<class U> struct C { };\n};\ntemplate<> struct A<int> {\nvoid f(int);\n};\nvoid h() {\nA<int> a;\na.f(16);\n}\n// A<int>::f must be defined somewhere\n// template<> not used for a member of an\n// explicitly specialized class template\nvoid A<int>::f(int) { /\xe2\x88\x97 ... \xe2\x88\x97/ }\n