引用包装器

函数副本机制:

#include <iostream>

template<class T>
void com(T arg)
{
	arg++;
}

void main()
{
	int count = 10;
	com(count);
	std::cout << count << std::endl;
	system("pause");
}

 因为两个count的地址就跟不一样。

 

模板函数,引用无效,引用包装器才有效

#include <iostream>

template<class T>
void com(T arg)//模板函数,引用无效。只有引用包装器才有效。
{
	arg++;
}

void main()
{
	int count = 10;
	int &rcount = count;
	com(count);
	std::cout << count << std::endl;
	com(&count);//此时传入地址
	std::cout << count << std::endl;
	com(rcount);
	std::cout << count << std::endl;
	

	//std::ref(变量),引用包装器,函数模板里直接引用
	com(std::ref(count));
	std::cout << count << std::endl;

	system("pause");
}

 

探究不使用引用包装器时,直接引用,在模板函数,和主函数里面,变量的地址。

#include <iostream>

template<class T>
void com(T arg)//模板函数,引用无效。只有引用包装器才有效。
{
	std::cout << "com" << &arg << "\n";
	arg++;
}

void main()
{
	int count = 10;
	int &rcount = count;
	com(rcount);
	std::cout << "main=" << &rcount << "\n";

	system("pause");
}

 相当于模板函数引用无效

切记,使用模板函数时,引用时及主要使用引用包装器。

用于场景,往函数模板传递参数时,想通过函数模板改变main函数里的数时,需要用到引用包装器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值