为什么编译器在重载时停止名称查找? [英] Why does the compiler stops the name lookup on overloads?

查看:49
本文介绍了为什么编译器在重载时停止名称查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚读了这篇文章:使用C ++的乐趣命名空间
作者表明,编译器在遇到第一个过载时会停止寻找重载,此处使用的是命名空间。

I just read this article:Fun with C++ namespaces Where the author shows that the compiler stops looking for overloads when encountering the first one, here by using namespaces.

namespace A
{
   void f(int x); // like our std::sqrt(double)
}

namespace B
{
   struct S {}; // user-defined type with associated namespace B

   void f(S);
   void f(int, int);

   void test1()
   {
      using namespace A; // using DIRECTIVE
      f(1);              // ERROR  namespace A is not considered because
                         //        B contains two overloads for 'f'
      f(1,2);            // OK     B::f(int,int)
      f(B::S());         // OK     B::f(S)
   }   

   void test2()
   {
      using A::f; // using DECLARATION
      f(1);       // OK     A::f(int)
      f(1,2);     // ERROR  A::f  hides  B::f(int,int)
      f(B::S());  // OK     B::f(S) due to ADL!
   }
}

namespace C
{
   void test3()
   {
      using namespace A; // using DIRECTIVE
      f(1);              // OK     A::f(int)
      f(B::S());         // OK     B::f(S) due to ADL!
   }   

   void test4()
   {
      using A::f; // using DECLARATION
      f(1);       // OK     A::f(int)
      f(B::S());  // OK     B::f(S) due to ADL!
   }
}

为什么编译器应该停止?

Why is the compiler supposed to stop?

编辑#1:问题的实质确实是:标准为何这么说?

EDIT #1: The question is indeed ment to be: Why does the standard says so?

感谢所有

推荐答案


在遇到第一个编译器时,编译器将停止寻找重载

the compiler stops looking for overloads when encountering the first one

不,它不会停止遇到第一个时,否则您将找不到两个 B :: f(int,int) B :: f(S)

No, it doesn't stop "when encountering the first one" otherwise you couldn't find both B::f(int,int) and B::f(S).

它将查找给定范围(不仅是第一个)中的所有重载,但在更远的范围中查找不会更远。

It finds all overloads in a given scope (not only the first one), but then doesn't look further in more distant scopes.

这与C ++中的所有名称查找一样,如果您有一个名为 var 的全局变量,并且在某些函数中有一个名为 var 的局部变量,在函数中使用该名称将引用该局部变量。这样更有用,因为您打算使用在附近声明的变量,因为它在相关代码中。

That's like all name lookup in C++, if you have a global variable called var and in some function you also have a local variable called var, using the name within the function will refer to the local variable. It's more useful that way, it's more likely that you meant to use the variable that is in declared nearby, as it's in related code.

如果有人递给您一封信,并且告诉您将它送给站在几米外的弗雷德(Fred),他戴着一个写着我是弗雷德的徽章,您会不理him他,走到外面继续寻找世界上每个叫弗雷德的人吗?

If someone hands you a letter and tells you to give it to Fred, who is standing a few metres away wearing a badge that says "I am Fred", would you ignore him and go outside and keep looking for every other person in the world called Fred?

这篇关于为什么编译器在重载时停止名称查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆