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

Why are reference template parameters not deduced automatically?

本文关键字:参考 参数 为什么      更新时间:2023-10-16

在下面的示例中,我直观地期望呼叫inc(iref)使用T=int&调用INC功能,因为这是iref的类型。但是,当变量传递到函数时,&似乎已删除,因此在inc(i)inc(iref)的情况下导致T=int。我期望的行为仅在明确指定模板参数为参考时才发生。

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&amp;或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;
}