为什么编译器无法找出此函数引用的正确重载?
Why can't the compiler figure out the right overload for this function reference?
为什么它不选择正确的重载?我得到错误:
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();
也是有歧义的
不能通过返回类型重载;
相关文章:
- 取消引用运算符不能重载
- 错误:无法解析对重载函数的引用;你的意思是调用它吗?
- 传递空初始值设定项列表时使用右值和左值引用候选项的重载解析
- 为什么我的运算符 + 重载尽管是通过引用传递的,但仍调用我的复制构造函数?
- C++编程:运算符重载中的引用如何工作?
- 重载运算符*以获取对另一个类的实例的引用
- 对运算符=使用通用引用,而不是多个重载
- 如何重载下标运算符 [] 以引用 2d STL 数组?
- 具有参数包和通用引用的重载选择
- 有什么理由用右值引用重载运算符吗?
- 封装 ublas 并将常量引用重载到 operator()
- std::forward() 的右值引用重载的目的是什么?
- std::move into static_pointer_cast:为什么static_pointer_cast没有右值引用重载?
- 通过引用重载多个函数对象
- C++ 右值引用重载,而不是移动构造函数
- 通过引用重载运算符-C++来传递对象
- 指针和引用 + 重载运算符
- 当基类型为函数引用时,右值引用重载
- 在没有歧义的情况下,是否允许通过引用重载函数
- 是否需要为const和通用引用重载?