c++ - 通常对函数名的非限定查找与对变量名的查找不同吗?

标签 c++ function language-lawyer

考虑以下代码:

#include <iostream>

int a=5;//1
extern int a;//2

int main(){ cout << a; }

在非限定名称查找期间,将找到#1,非限定名称查找在找到#1 后立即结束。

但考虑另一个例子:

#include <iostream>

void foo() { cout << "zero arg"; }
void foo(int a) { cout << "one arg"; }

int main(){ foo(4); }

在那种情况下,void foo(); 的定义将首先被找到。但不合格的名称查找并没有结束。为什么? 标准中哪里规定的?总的来说,我感兴趣的是:

函数调用的后缀表达式的非限定名称查找何时结束?

注意:我知道 ADL 是什么意思。在这种情况下,ADL 生成的声明集是空的。

更新:

但是如果我们这样写:

int foo(int a) { return 0; }
namespace A
{
    int foo() { return 1; }
    int a= foo(5); //Error: to many arguments
}

这意味着不考虑封闭的命名空间。我也想知道它在哪里指定。

最佳答案

In that case void foo();'s definition will be found first. But unqualified name lookup doesn't end. Why?

因为标准说:

Name lookup may associate more than one declaration with a name if it finds the name to be a function name; the declarations are said to form a set of overloaded functions (13.1). Overload resolution (13.3) takes place after name lookup has succeeded.

因此在函数的情况下,名称查找在找到第一个匹配项后不会结束,它会收集所有名称,然后重载解析发生。

更新

对于更新的问题,您返回到您的 previous question

name lookup ends as soon as a declaration is found for the name.

因此,一旦在 inner scope 中找到 foo,就不会进行进一步的搜索。

但是如果你使用namespace qualified 名称,那么指定的命名空间将被搜索:

int a = ::foo(5); // finds foo in global namespace.

所以一般来说,对于非限定搜索,首先在当前范围内进行搜索,如果没有找到则在下一个封闭范围内搜索,依此类推。但是,一旦找到一个名字,搜索就结束了,这个名字是否可用并不重要。这意味着,对于功能,它可能不是正确的,可能在正确的封闭范围内有一个重载,但搜索不会继续到那个。

关于c++ - 通常对函数名的非限定查找与对变量名的查找不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23966793/

相关文章:

c++ - 如何为类声明友元函数?

c++ - 尝试通过 using-declaration 定义命名空间成员

c++ - 与 Minecraft bukkit 服务器握手 - 发送服务器主机字段失败

c++ - 使用 c/c++ 的文件 IO 技巧

php - PHP echo 和 PHP return 用纯英语有什么区别?

从数组转换为指针。我错过了什么吗?

c++ - memcpy 是可简单复制的类型构造还是赋值?

c++ - 函数模板重载区别

c++ - 可以在 C++ 中调用缺少模板参数的模板函数吗?

c++ - 虚函数的引用