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

此条款意思大概就是说在类模板中,在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
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值