模板类的成员函数可以完全专门化,例如
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; }
可以毫无问题地编译。请注意,这foo()
不是模板函数,因此这与模板函数专业化无关(我可以理解部分专业化是不允许的,因为它与重载结合起来会变得非常混乱)。在我看来,上面的代码只是以下模板类专业化的简写:
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; }
由于第二个片段是合法的,而第一个片段将完全等同于它(但我不必显式复制所有其他数据成员并永远并行维护它们),我不明白为什么不允许第一个片段。
我知道这个问题已经在这里和这里被问过,但我不是在寻找“确实不允许”类型的答案。或“这是不允许的,因为标准说不允许。”,也没有解决这个问题的方法。我想知道为什么标准不允许这样做,即这是有根本原因还是将来会被允许?到目前为止,我在任何明显的重复问题中都没有发现这一点。