简体   繁体   中英

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 . 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) . The behaviour I'd expect only happens when explicitly specifying the template parameter as reference.

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:

  • Why is the reference seemingly turned into a 'bare' value when being passed via inc(iref) ? What's the process behind it?
  • Why does it work this way / what's the rationale behind that design decision? Would there be any problems or negative consequences if it worked the way I intuitively expected?

The reference is stripped of it's reference value because if it isn't iref is ambiguous otherwise(int& or 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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