繁体   English   中英

为什么不自动推导参考模板参数?

[英]Why are reference template parameters not deduced automatically?

在下面的示例中,我很直观地期望对inc(iref)的调用将使用T=int&调用inc(iref)函数,因为这是iref的类型。 但是,似乎在将变量传递给函数时会删除& ,因此在inc(i)inc(iref)的情况下都导致T=int 我期望的行为仅在显式指定template参数作为引用时发生。

template<typename T> 
void inc(T t) {
    t++;
}

int main() {
    int i = 41;
    int& iref = i;

    iref++;
    std::cout << i << " " << iref << std::endl; // prints 42 42, as expected

    inc(i);
    std::cout << i << " " << iref << std::endl; // still prints 42 42, as expected

    inc(iref);
    std::cout << i << " " << iref << std::endl; // prints 42 42, instead of 43 43

    inc<int&>(iref);
    std::cout << i << " " << iref << std::endl; // now finally prints 43 43
}

因此,我的问题是:

  • 当通过inc(iref)传递引用时,为什么引用似乎变成了“裸”值? 它背后的过程是什么?
  • 为什么这样工作/设计决定的依据是什么? 如果它按照我的直觉预期的方式工作,将会有任何问题或负面后果吗?

该引用被剥夺了它的引用值,因为如果不是,则iref是不明确的(int&或int)。 它的设计方式使您可以像这样重载它:

#include <iostream>

template<typename T> 
void inc(T& t) {
    t++;
}

int main() {
    int i = 41;
    int& iref = i;

    inc(iref);
    std::cout << iref << std::endl;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM