为什么编译器无法找出此函数引用的正确重载?

Why can't the compiler figure out the right overload for this function reference?

本文关键字:引用 重载 函数 编译器 为什么      更新时间:2023-10-16

为什么它不选择正确的重载?我得到错误:

main.cpp:4:7: error: new declaration ‘int f()’
main.cpp:3:6: error: ambiguates old declaration ‘void f()’

void f() {}
int f() { return 0; }
int main() {
    void (&x)() = f;
    x();
}

根据c++标准,13.2.1

如果两个同名的函数声明在同一作用域中并且具有相同的形参声明,则它们引用同一个函数。

这意味着只考虑名称和参数类型;

这是有意义的,因为您可以调用带有返回值的函数,而忽略它的返回值。如果语言设计者允许在返回类型上重载,编译器将无法在某些合法上下文中解析这些重载。

不能按返回类型重载,因为:

int main() {
   f();  // call to void f
   f();  // call to int returning one
   f();  // call to void
   return 0;
}

都是二义性的

float f() { return 0.0f; }
char  f() { return 'a';  }
int   i = f();

也是有歧义的

不能通过返回类型重载;