案例一:
template<class T>
class A{
public:
A(T*)
{
cout<<"T*"<<endl;
}
template<class Y>
A(Y*)
{
cout<<"Y*"<<endl;
}
};
然后调用:
A<int>p1(new int); //T*
A<int>p2(new double); //Y*
这个案子我能理解。
案例B:
template<class T>
class B{
public:
template<class Y>
B(Y*)
{
cout<<"Y*"<<endl;
}
};
然后调用:
B<int>p3(new int); //Y*
B<int>p4(new double); //Y*
问题:
我无法理解案例 B 并弄清楚为什么要B<int>p3(new int);
打电话B(Y*)
?有人知道为什么吗?
使用模板构造函数,类型参数的类型推导Y
不依赖于T
您使用 显式指定的类型参数B<int>
。
这意味着在以下情况下:
B<int>p3(new int)
Y
是int
从 type 的参数推导出来的int*
。
同样,在以下情况下:
B<int>p4(new double)
Y
是double
从 type 的参数推导出来的double*
。
类模板类型参数T
和构造函数模板类型参数之间没有联系Y
——它们的推导是分开进行的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句