effective c++ 条款45 -- 运用成员函数模板接受所有兼容类型

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HLW0522/article/details/82960711

此条款意思大概就是说在类模板中,在copy构造与赋值操作中要兼容所有可能类型。

考虑一下代码:

template<class T>
class C
{
public:
	C(T a) :m_t(a) {}
	C(const C& c) 
	{
		cout << "copy 1" << endl;
	}
	template<class U>
	C(const C<U>& c)
	{
		cout << "copy 2" << endl;
	}

	C& operator=(const C&)
	{
		cout << "operator 1" << endl;
		return *this;
	}
	template<class U>
	C& operator=(const C<U>&)
	{
		cout << "operator 2" << endl;
		return *this;
	}

private:
	T m_t;

};

void main()
{
	
	C<int>c(10);
	C<int>c2(c);// 以C<int>类型构造 C<int>类型
	C<double> c3(c);//以C<int>类型构造 C<double>类型
	
	C<int>c4(0);
	C<double>c5(0);
	
	c = c4; //C<int>类型赋值给C<int>
	c2 = c5; //C<double>类型赋值给C<int>


	system("pause");	
}

输出为:

copy 1
copy 2
operator 1
operator 2

如果想控制copy构造的方方面面就必须要同时声明泛化copy构造与正常的copy构造。此处只给出了同类型的与不同类型的两种。也可以更具体的给出其他类型。书上实例如下

template<class T>
class shared_ptr
{
public:
	template<class Y>                                   // 构造,来自任何兼容的
	explicit shared_ptr(Y* p);                         //内置指针
	template<class Y>
	shared_ptr(shared_ptr<Y> const& r);                //或shared_ptr、
	template<class Y>
	explicit shared_ptr(weak_ptr<Y> const& r);         //或weak_ptr、
	template<class Y>
	explicit shared_ptr(auto_ptr<Y>& r);               //或auto_ptr  
	template<class Y>                                        //赋值,来自任何兼容的
	shared_ptr& operator=(shared_ptr<Y> const& r);           //shared_ptr
	template<class Y>                                                                 
	shared_ptr& operator=(auto_ptr<Y>& r);                    //或auto_ptr
};

猜你喜欢

转载自blog.csdn.net/HLW0522/article/details/82960711
今日推荐