C++的拷贝构造函数要求源对象的类型必须与将要构造的对象保持一致,这对于模板类来说有点小小的问题:
#include <string>
#include <iostream>
using namespace std;
template<class T>
class A{
public:
A()=default;
A(const A& a): m(a.m)
{
cout<<"copy contruction"<<endl;
}
T m;
};
int main()
{
A<int> a;
A<int> b(a);
A<long> c(a); //无法编译,因为a是A<int>型,于要构造的A<long>不匹配
return 0;
}
可以通过增加一个模板拷贝构造函数解决这个问题:
#include <string>
#include <iostream>
using namespace std;
template<class T>
class A{
public:
A()=default;
A(const A& a): m(a.m)
{
cout<<"copy contruction"<<endl;
}
template<class O>
A(const A<O>& o) : m(o.m)
{
cout<<"template copy contruction"<<endl;
}
T m;
};
int main()
{
A<int> a;
A<int> b(a); //输出:copy contruction
A<long> c(a); //输出:template copy contruction
return 0;
}