模板类的成员函数可以是完全专用的,例如,为什么你不能部分专门化一个类成员函数?
template<class A>
struct MyClass {
// Lots of other members
int foo();
};
template<class A>
MyClass<A>::foo() { return 42; }
template<>
MyClass<int>::foo() { return 0; }
会编译没有问题。请注意0不是模板函数,所以这不是模板函数专业化(我可以理解,部分专业化是不允许的,因为它会与重载结合起来令人难以置信的混淆)。在我看来,上面的代码只是为了下面的模板类专业化的缩写:
template<class A>
struct MyClass {
// Lots of other members
int foo();
};
template<class A>
MyClass<A>::foo() { return 42; }
template<>
struct MyClass<int> {
// Copy all the other members from MyClass<A>
int foo();
};
template<>
MyClass<int>::foo() { return 0; }
这是正确的吗?
在这种情况下,我不知道为什么一个部分专业化有类似简写是不允许的,即为什么我不能写
template<class A, class B>
struct MyClass {
// Lots of other members
int foo();
};
template<class A, class B>
MyClass<A,B>::foo() { return 42; }
template<class B>
MyClass<int,B>::foo() { return 0; }
的简写
template<class A, class B>
struct MyClass {
// Lots of other members
int foo();
};
template<class A, class B>
MyClass<A,B>::foo() { return 42; }
template<class B>
struct MyClass<int,B> {
// Copy all the other members from MyClass<A,B>
int foo();
};
template<class B>
MyClass<int,B>::foo() { return 0; }
由于第二个片段是合法的,第一个片段是合法的,第一个片段与其完全相同(但没有我必须明确复制所有其他数据成员并永久保持它们),我不明白为什么第一个不允许。
我知道这个问题已经被问到here和here,但我不是在寻找类型为“确实不允许”的答案。或者“这是不允许的,因为标准说不是”,也没有办法规避这个问题。我想知道为什么该标准不允许它,即是否有一个基本的原因或未来可以允许?到目前为止,我没有发现任何明显重复的问题。
这个问题经常被问到。长的答案在这里:http://www.gotw.ca/publications/mill17.htm –
我可能是错的,但我认为这篇文章是关于专门*模板函数*。我的问题是关于专门化*模板类*的非模板*成员函数,在我看来,它实际上专门化了类而不是函数(因为成员函数不是模板)。 – PieterNuyts
MyClass (例如)是与MyClass 不同的类。尝试为成员函数专门化模板类的模板类型是没有意义的。 –