函数副本机制:
#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");
}
相当于模板函数引用无效