【问题标题】:3.4.1 Unqualified name lookup and function overloading3.4.1 非限定名称查找和函数重载
【发布时间】:2014-05-10 06:06:47
【问题描述】:

我读过关于非限定名称查找的内容,但我对函数重载有一个误解。在N3797中说:

在 3.4.1 中列出的所有情况下,都会在范围内搜索 按各个类别中列出的顺序声明; 一旦找到名称的声明,名称查找就会结束。

考虑以下代码sn-p:

#include <stdio.h>

void foo(int)
{
    printf("foo(int)\n");
}

void foo()
{
    printf("foo(void)\n");
}

int main()
{
    foo();
}

这个程序显然打印了foo(void)。在这种情况下,名称foo 将在范围内搜索声明。并且让 foo 的第一个成立的定义是

void foo(int)
{
    printf("foo(int)\n");
}

为什么程序找到名字后还要继续寻找被调用函数的最佳重载。

【问题讨论】:

    标签: c++ function scope overloading


    【解决方案1】:

    来自标准:

    Name lookup may associate more than one declaration with a name if  
    it finds the name to be a function name.  Overload resolution (13.3) takes
    place after name lookup has succeeded. 
    

    所以首先将可能的候选者整理出来,然后使用最合适的重载。

    一旦找到名称的声明,名称查找就结束并不意味着它在找到第一个声明时返回。它累积范围内所有匹配的名称,然后使用最合适的一个。在方法的情况下,如果它们都不能使用,那么它会出错,而不是在任何封闭范围内搜索。考虑以下代码:

    namespace  A
    {
        void f(double x){cout<<"A::f(double)\n";}
    
        void f(string s){cout<<"A::f(string)\n";}
    
        namespace B
        {
            void f(int x){cout<<"B::f\n";}
    
            void call()
            {
                f(10); // calls B::f
                f(10.5); // calls B::f even if better matching method is present in A
                f("Hi"); // error, does not search in A
            }
        }
    }
    

    【讨论】:

    • 第二段写错了。名称查找停止在找到名称的范围内,它会在该范围内找到与该名称匹配的所有声明。即使那里可能有更好的匹配功能,它也不会继续查看封闭范围。然后还有 ADL,这是另一回事。
    • +1 @jrok,你是对的。第二段也说,虽然没有提到在范围内。实际上第一行取自问题,其中明确定义了scope
    • @jrok 你说过Name lookup stops in the scope in which a name is found and it finds all declarations in that scope matching that name。但我在标准中找不到。可以参考一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    相关资源
    最近更新 更多