c++ - 代码在 Visual Studio 2010 中编译但根本不应该编译

标签 c++ compiler-errors

以下源代码可使用 Visual Studio 2010 正确编译:

namespace NS
   {
   class X
      {
      };   
   X Y(X str);
   } 

void myFun()
   {
   NS::X x;
   Y(x);
   }

(这是简化的代码,其中我自己的所有类和函数名称都已替换为 X、Y、...)

我预计 Y(x) 行将无法编译,因为它应该是 NS::Y(x)

这段源码是用下面的命令编译的

cl /c file.cpp

这里没有包含其他文件,没有其他命令行选项。

为什么这个文件可以编译? VS2010 中的错误?或者我(和我的其他 3 位同事)忽略了什么?

最佳答案

您遇到的问题是 ADL ( Argument Dependent Lookup ) 造成的。

您的代码段没有任何问题(除了链接器可能会提示 NS::Y 未定义这一事实),但它应该编译 - VS2012 正在处理代码段应该。

编译器会找到 NS::Y,因为参数 x (NS::X) 的类型在适当的范围。


3.4.2 Argument-dependent name lookup [basic.lookup.argdep]

  1. When an unqualified name is used as the postfix-expression in a function call (5.2.2), other namespaces not considered during the usual unqualified lookup (3.4.1) may be searched, and in those namespaces, namespace-scope friend function declarations (11.4) not otherwise visible may be found.

    These modifications to the search depend on the types of the arguments (and for template template arguments, the namespace of the template argument).

  2. For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero or more associated classes to be considered.

    The sets of namespaces and classes is determined entirely by the types of the function arguments (and the namespace of any template template argument).

关于c++ - 代码在 Visual Studio 2010 中编译但根本不应该编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9819782/

相关文章:

c++ - 企业架构师错误 : Unexpected symbol fix?

c++ - 如何将 CComVariant bstr 转换为 CString

C++ 11 : Mutex & Condition Variable Cannot be Copied

c++ - g++未知/tmp/cc21HhMd.o:在函数`main::{lambda(编译错误

compiler-errors - 我对游戏制作人有一个神秘的错误

css - Mediawiki - 脚本错误 : Lua error at line 1: unexpected symbol near '/'

c++ - 简单的模板继承问题C++

c++ - 为什么传递 shared_from_this() 会导致段错误?

asp.net - 运行测试时出错: "You must add a reference to assembly..."

css - SASS错误与编译