首页 >社区问答列表 >c++函数模板实参推断

c++函数模板实参推断

为什么向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;
}

bVEBi0.png

  • 代言
  • 代言    2016-11-11 14:28:483楼

    如果需要,你可以指定模板参数的。使用com(temp);这样的方式来使用引用类型参数。

    下面的代码试试

    #include 
    #include 
    using namespace std;
    
    int main()
    {
      int x = 1000;
      int& rx = x;
      cout<

                     


    +0添加回复

  • 回复
  • 代言
  • 代言    2016-11-11 14:28:192楼

    你的问题出在对引用的理解,和模板没有关系。
    引用即别名,所以rtemp和temp都是代表同一个内存位置。它们作为普通函数参数传入的时候函数得到的是复制后的局部变量,所以它们不会被修改。但作为引用传入的时候,函数得到的是temp或rtemp本身,可以修改。

    +0添加回复

  • 回复