我看过许多 StackOverflow 帖子,它们说类模板成员函数的特化在 C++ 中是不合法的,除非封闭类也是特化的。
但是,另一篇帖子似乎表明可以专门化成员模板函数,只要专门化函数的定义出现在模板类的类声明中,如下所示:
template<typename T1, typename T2>
class A
{
public:
template<typename TX> TX foo() {return 0;};
template<> T1 foo<T1>() {return 1;}; // provide the specialization's definition within the class declaration: works
//template<> T1 foo<T1>(); // ... switch to this (and provide the definition below), and it's a compile error
};
// This function definition is only present when the commented-out line of code in the class declaration is used
template<typename T1, typename T2>
template<>
T1 A<T1, T2>::foo<T1>()
{
return 1;
}
int main(void)
{
A<int, double> a;
const int n = a.foo<int>(); // When the definition appears inside the class declaration, n is 1 - it works
return 0;
}
从我的代码示例中的注释可以看出,当在类声明中提供了专用函数的定义时,代码构建没有错误,并且运行成功,并且n
in function的main()
值为1
,正如预期的那样。
但是,当将专用函数定义移到类声明之外,但保持不变时,如图所示,编译器会发出其他帖子已经指出的错误;就我而言(Visual Studio 2010),错误是an explicit specialization of a template member must be a member of an explicit specialization
.
我的问题是这个。如果除非封闭的模板类也是特化的,否则不允许在类模板中显式特化成员函数,那么如果在类声明中提供了定义,为什么它在我的示例代码中起作用?