在寻找一些错误时,我偶然发现了以下初始化行为,这对我来说似乎很奇怪:虽然初始化检查现有构造函数,但似乎存在忽略拟合构造函数模板的情况。例如,考虑以下程序:
#include <iostream>
template<class T>
struct A {
A() {};
template<class S>
A(const A<S>& a) {std::cout << "constructor template used for A" << std::endl;};
};
template<class T>
struct B{
B() {};
B(const B<int>& b) {std::cout << "constructor used for B" << std::endl;};
};
int main() {
A<int> a;
B<int> b;
A<int> aa = a;
B<int> bb = b;
A<double> aaa = a;
}
对我来说,这会产生输出
constructor used for B
constructor template used for A
这意味着它不使用 main 的第三行中的构造函数。为什么不?有原因吗?或者我的语法在某个地方?该模板似乎有效,因为它已在最后一行中成功使用。
我知道这个例子看起来过于复杂,但各种简化使我想要展示的行为消失了。另外:初始化将使用模板特化,这是我目前如何防止这导致错误(首先导致错误的地方)。
如果我的问题有任何问题,我很抱歉,我不是程序员,我不是母语人士,这是我的第一个问题,请原谅我。
最佳答案
编译器提供了一个隐式声明的非模板复制构造函数,其签名等价于
A(const A& a);
因为 模板构造函数不被视为用户定义的复制构造函数,即复制构造函数必须是非模板。
隐式声明的复制构造函数在重载解析中比模板版本更匹配,并且是在从
A<T>
复制构造 A<T>
时被调用的构造函数。这可以用一个简单的例子来说明,用户定义了 A(const A&)
:#include <iostream>
template<class T>
struct A
{
A() {};
A(const A& a) {
std::cout << "copy constructor used for A" << std::endl;
}
template<class S>
A(const A<S>& a) {
std::cout << "constructor template used for A" << std::endl;
}
};
int main()
{
A<int> ai;
A<double> ad = ai; / calls template conversion contructor
A<int> ai2 = ai; // calls copy constructor A(const A&);
}
关于c++ - 初始化忽略构造函数模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15115859/