以下代码适用于 Visual Studio 2008,但不适用于 GCC/G++ 4.3.4 20090804。根据 C++ 标准,哪种行为正确?
template <int N>
struct A : A<N-1> {};
template <>
struct A<0> {};
struct B : A<1> {};
template <int N>
void Func(const A<N> &a) {}
int main()
{
A<1> a; //is derived from A<0>
Func(a); //vs2008: ok, g++: ok
//Comeau: ok
B b; //is derived from A<1>
Func(b); //vs2008: ok, g++: error, no matching function for call to Func(B&)
//Comeau: error: no instance of function template "Func" matches the
// argument list. The argument types that you used are: (B).
return 0;
}
如果我用
重载 Func()void Func(const A<0> &a) { std::cout << '0'; }
void Func(const A<1> &a) { std::cout << '1'; }
总是调用后一个(如预期的那样)。所以我也希望使用 N=1 调用模板化函数,因为 A<1> 是 B 的直接基础。这个假设真的错误吗?
1>
最佳答案
在浏览了 N3035 之后,我在第 14.9.2.1.4 节中找到了这个:
If P is a class and P has the form simple-template-id, then the transformed A can be a derived class of the deduced A. Likewise, if P is a pointer to a class of the form simple-template-id, the transformed A can be a pointer to a derived class pointed to by the deduced A.
但是在 14.9.2.1.5 中,它说:
These alternatives are considered only if type deduction would otherwise fail. If they yield more than one possible deduced A, the type deduction fails.
是这样的:A<1>和 A<0>被视为 B 的基类.
我猜这对 Visual Studio 来说意味着否定(至少,如果当前标准是这样说的:读者练习)。
关于c++ - GCC/VS2008 : Different behaviour of function call when templated base class is derived from itself,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2392515/