使用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;
}