为什么向com中传递一个引用,无法改变temp的值,而向com1中传递就可以改变呢?难道com这个函数模板传入引用时,不是推断出和com1一样的实例吗?
#include <iostream>
#include <typeinfo>
template <typename T>
void com(T arg) {
std::cout << "com arg's address = " << &arg << std::endl;
arg++;
}
void com1(int& arg) {
std::cout << "com1 arg's address = " << &arg << std::endl;
arg++;
}
int main(){
int temp(10);
std::cout << "main temp's address = " << &temp <<std::endl;
int& rTemp(temp);
std::cout << "main rTemp's address = " << &rTemp <<std::endl;
com(temp);
std::cout << temp <<std::endl;
com(rTemp);
std::cout << temp <<std::endl;
com1(rTemp);
std::cout << temp <<std::endl;
return 0;
}
你写void com(T& arg)试试