模板复构函数(pair结构体引起的思考(强迫症犯了))

在一个模板类中,复构函数和模板复构函数同时存在时,优先调用复构函数。 只有当确切符合模板复构函数的接口时,才调用模板复构函数。 编译器永远不会把模板复构函数视为复构函数,即使用户没有自己定义复构函数,编译器也会生成一个默认的复构函数。

#include <iostream>
using namespace std;
template <class T>
struct test {

	T d;

	test(T _d = 0) : d(_d) { cout << "This is a Constructor. " << endl; };
	//test(test<T> & tmp) : d(tmp.d) { cout << "This is a copy Constructor. " << endl; };


	template <class U> //模板复构函数
	test(const test<U> & tmp):d(tmp.d)
	{
		cout << "This is a template copy constructor." << endl;
	}

	T getdata() { return d; }
};
int main()
{
	test<int> a(10);
	test<int> b(a); //调用复制构造函数,即使在该模板类中用户没有自定义该函数,编译器也会生成一个默认复制构造函数。因为编译器永远不会认为一个模板构造函数是一个构造函数

    test<double> c(a); //调用模板复制构造函数

	system("pause");
	return 0;
}


结果:
在这里插入图片描述

可见,test<int> b(a);调用的是默认的复构函数;test<double> c(a);调用模板复制构造函数。

接下来分析pair结构体就轻松多了:
pair定义在< utility >中,是一个结构体模板,这意味着pair的所有成员都是public,可以方便的存储成员变量。


#include<iostream>
#include <string>
using namespace std;

template<class T1, class T2>
struct Pair {
	T1 first;
	T2 second;

	Pair()//A无参构造函数
		: first(T1()), second(T2()) {}

	Pair(const T1& x, const T2& y)//B有参构造函数
		: first(x), second(y) {}

	Pair(const Pair<T1, T2> &p)       //C复制构造函数
		: first(p.first), second(p.second) {
		cout << "copy constructor" << endl;
	}


	template<class U, class V> Pair(const Pair<U, V> &p)//D模板复制构造函数
		: first(p.first), second(p.second) {
		cout << "template copy constructor" << endl;
	}



};
int main() {

	Pair<int, char*> pair_a(2, "abc");//无参的构造函数
	Pair<int, char*> pair_t(pair_a);  //复制构造函数,即使C被注释掉,也会调用默认的复制构造函数,而不会调用模板复制构造函数
	Pair<int, string> pair_s = pair_t;//模板复制构造函数,隐式类型转换
	pair_t.first = 1;
	pair_t.second = "shenhang";
	cout << "pair_t.first:" << pair_t.first << endl;
	cout << "pair_t.second:" << pair_t.second << endl;
	cout << "pair_s.first:" << pair_s.first << endl;
	cout << "pair_s.second:" << pair_s.second << endl;


	system("pause");
	return 0;
}

结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值