[英]Why are reference template parameters not deduced automatically?
In the following example, I'd intuitively expect the call to inc(iref)
to invoke the inc-function with T=int&
, since that's the type of iref
. 在下面的示例中,我很直观地期望对
inc(iref)
的调用将使用T=int&
调用inc(iref)
函数,因为这是iref
的类型。 However, it seems that the &
is dropped when the variable is passed to a function, thus leading to T=int
in the case of both inc(i)
as well as inc(iref)
. 但是,似乎在将变量传递给函数时会删除
&
,因此在inc(i)
和inc(iref)
的情况下都导致T=int
。 The behaviour I'd expect only happens when explicitly specifying the template parameter as reference. 我期望的行为仅在显式指定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
}
So, my questions are: 因此,我的问题是:
inc(iref)
? inc(iref)
传递引用时,为什么引用似乎变成了“裸”值? What's the process behind it? The reference is stripped of it's reference value because if it isn't iref is ambiguous otherwise(int& or int). 该引用被剥夺了它的引用值,因为如果不是,则iref是不明确的(int&或int)。 It is designed this way so that so that you may overload it like:
它的设计方式使您可以像这样重载它:
#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.