-1

考虑以下函数

int f (const int& i)
{
  cout << "in const reference function";
}
int f ( int &i)
{
  cout << "in non const reference function";
}
int main()
{
    int i;
    f(3);
    f(i);
}

在这种情况下,当函数调用与函数定义绑定时,它是在编译时还是运行时,因为一个是左值i而另一个不是?

除此之外,这两个函数在参数的数量和类型方面是相同的。

4

3 回答 3

1

重载将在编译时选择。将选择“最佳拟合”,在这种情况下取​​决于函数参数的 cv 限定:

来自 N4140 [over.ics.rank]/3

除非以下规则之一适用,否则两个相同形式的隐式转换序列是无法区分的转换序列:

  • 标准转换序列 S1 是比 S2 更好的转换序列,如果

    • ...

    • S1 和 S2 是引用绑定,并且引用所引用的类型除了顶级 cv-qualifiers 之外是相同的类型,并且 S2 初始化的引用所引用的类型比由 S1 初始化的引用引用。

int&的 cv 合格率低于const int&,因此将尽可能选择。int&无法绑定到 rvalue 之类的3,因此const为此选择了版本。

Demo

于 2015-07-21T08:48:25.720 回答
0

它是在编译时定义的这段代码:

void f (const int& i)
{
    return;
}
void f ( int &i)
{
    return;
}
int main()
{
    int i = 12;
    f(3);
    f(i);
}

用 gcc 5.2 编译到这个:

movl    $3, -4(%rbp) //Declare variable i with 3
leaq    -4(%rbp), %rax
movq    %rax, %rdi
call    f(int const&)  //And call the method with const int&
leaq    -8(%rbp), %rax 
movq    %rax, %rdi
call    f(int&) //Call the method with only the reference
于 2015-07-21T08:49:25.373 回答
0

这将仅在编译时完成,因为参数的类型不同。因此,这些不是简单的重载函数,它们的调用只能在编译时确定。

于 2015-07-21T08:49:47.423 回答