Overloading reference vs const reference

后端 未结 2 1157
有刺的猬
有刺的猬 2020-12-15 11:42

I have the following code:

#include 

template 
void f(T& x)        
{
    std::cout << \"f(T& )\" << s         


        
2条回答
  •  [愿得一人]
    2020-12-15 12:14

    Given two competing overloads, the standard requires the compiler to select the overload that has the "best fit". (If there's no unique best overload, or if the unique best overload is inaccessible, the program is ill-formed.)

    In this case, the rules are provided by §13.3.3.2 [over.ics.rank]/p3:

    Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if:

    • [...]

    • S1 and S2 are reference bindings (8.5.3), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.

    This is the example given in the standard:

    int f(const int &);
    int f(int &);
    int g(const int &);
    int g(int);
    int i;
    int j = f(i); // calls f(int &)
    int k = g(i); // ambiguous
    

    In your case, const T& is more cv-qualified than T&, so by the standard, f(T&) is a better fit than f(const T&) and is selected by overload resolution.

提交回复
热议问题