c++ref()函数

使用std::ref可以在模板传参的时候传入引用,否则无法传递

#include<iostream>

template<class T>
void com(T arg)
{
	std::cout <<"com ="<< &arg << "\n";
	arg++;
}


void main()
{
	int count = 10;
	int  & rcount = count;
	com(count);
	std::cout << count << std::endl;//10
	com(rcount);
	std::cout << "main=" << &rcount << "\n"; 
	std::cout << count << std::endl;//10
	
	com(std::ref(rcount));//传引用
	std::cout << count << std::endl;//11
	
	std::cin.get();

}

ref()方法的返回值是reference_wrapper类型,这个类的源码大概的意思就是维持一个指针,并且重载操作符

template<class _Ty>
	class reference_wrapper
	: public _Refwrap_impl<_Ty>
	{	// stand-in for an assignable reference
public:
	typedef reference_wrapper<_Ty> _Myt;
	typedef _Refwrap_impl<_Ty> _Mybase;
	typedef _Ty type;

	reference_wrapper(_Ty& _Val) _NOEXCEPT
		: _Mybase(_Val)
		{	// construct
		}

	reference_wrapper(const _Myt& _Right) _NOEXCEPT
		: _Mybase(_Right.get())
		{	// construct by copying _Right
		}

	_Myt& operator=(const _Myt& _Right) _NOEXCEPT
		{	// assign _Right
		this->_Reset(_Right.get());
		return (*this);
		}

	operator _Ty&() const _NOEXCEPT
		{	// return reference
		return (this->_Get());
		}

	_Ty& get() const _NOEXCEPT
		{	// return reference
		return (this->_Get());
		}

	reference_wrapper(_Ty&&) = delete;
	};


#include<iostream>
template<class T>
void com(T arg)
{
	arg++;
	
}
template<class T>
struct MyStruct
{
	T &t;
	MyStruct(T &t):t(t){
		
	}
	T& get(){
		return &t;
	}
	 void operator++(int)    //后置形式
	{
		this->t++;
	}
};
using namespace std;
int main(){
	
	int count = 10;
	int  & rcount = count;
	MyStruct<int&> m(rcount);
	com(m);
	std::cout << rcount << endl;  //11
	getchar();
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值