我们知道,类里面提供一个缺省的拷贝构造函数(copy constructor)和拷贝赋值运算符(copy assignment operator)。所谓“缺省”,就是你自己不写出来,系统就自己为你生成。
我们来看下面一段代码:
template<class T>
class CT
{
public:
CT(){}
template<class X>
CT(const X& ref)
{
cout << "123" << endl;
}
};
int main( int argc , char* argv[] )
{
CT<int> f; //1
CT<int> obj(f); //2
return 0;
}
代码运行后并没有输出任何内容。注意了,上面出现了模板化构造函数(templated constructor)。看起来它有拷贝构造函数的形式,但它真的不是拷贝构造函数。真正的拷贝构造函数或者拷贝赋值运算符只对完全相同类型的对象施以构造或者赋值操作。而且,其如果是一个模板类的话,模板的参数也都必须相同。
Exception C++ 条款5中有这样一句话:Because a template constructor is never a copy constructor, the presence of such a template does not suppress the implicit declaration of a copy constructor. (因为模板构造函数终究不是拷贝构造函数,因此这种模板的出现并不会隐藏原来的拷贝构造函数之声明)
不要小看成员函数模板,它能提供一些易用的代码。