模板编程:不同类型相加采用模板重载操作符operator+,友元函数、declval、判断类型

重点:

1.表达式 declval<>可以在不需要使用默认构造函数(或者其它任意操作)的情况下为类型 T 生成一个值

2.模板友元重载operator+需要在类外定义

3.获取类内的值,定义成const是有原因的,其他要对成员进行处理会报错。

using namespace std;

//采用declval,表达式 declval<>可以在不需要使用默认构造函数
//(或者其它任意操作)的情况下为类型 T生成一个值
template<typename T1,typename T2>
struct PlusResultT
{
	using Type = decltype(std::declval<T1>() + std::declval<T2>());
};

//添加别名模板
template<typename T1, typename T2>
using PlusResult = typename PlusResultT<T1, T2>::Type;

template<typename T>
class Array
{
public:
	Array(T t) :val(t) {};
	~Array() = default;

	//添加const ,不然报错: 不能将“this”指针从“const Array<T>”转换为“Array<T> &”
	//val 它是const 而 GetVal 不是const, 因为 val 是常量一但涉及可能改变就会报错
	T GetVal() const{ return val;};

public:
	//采用友元函数,处理两个类型的时候
	template<typename T1, typename T2>
	friend Array<PlusResult<T1, T2>> operator+(const Array<T1>& t1, const Array<T2>& t2);
private:
	T val;
};


template<typename T1, typename T2>
Array<PlusResult<T1, T2>> operator+(const Array<T1>& t1, const Array<T2>& t2)
{
	return Array<PlusResult<T1, T2>>(t1.GetVal() + t2.GetVal());
};


//判断类型是否相同
template<typename T1,typename T2>
void printT()
{
	if (is_same_v<T1, T2>)
	{
		cout << "same type" << endl;
	}
	else
	{
		cout << "not same type" << endl;
	}
}

int main()
{
	Array<int> num(10);
	Array<char> ch('C');
	Array<int> num2(10);
	auto data=num + num2;
	printT<decltype(data.GetVal()), int>();
	printT<decltype(data.GetVal()), char>();
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值