这是一些显示奇怪的代码:
namespace ns
{
typedef int int_type;
class classus {
public:
int a = 0;
};
void print(classus c){
printf("a equals %i \n", c.a);
}
void print(int_type a){
printf("a equals %i \n", a);
}
}
int main(int argc, char* argv[])
{
ns::int_type a1 = 2;
ns::classus a2;
ns::print(a1); // this line wont work without explicit ns:: scope
print(a2); // this line works with or without explicit ns:: scope
}
它在Visual Studio 2017上构建并运行。Intellisense也对此感到非常满意。
似乎包含在名称空间中的class变量污染了该名称空间范围的整个行。这是错误还是功能?不管哪种方式,是否有关于此的一些文档...没有找到任何
使您感到困惑的功能称为ADL(依赖于参数的查找)
来自cppreference:
依赖于参数的查找,也称为ADL或Koenig查找,是用于在函数调用表达式中查找不合格函数名称的规则集,包括对重载运算符的隐式函数调用。除了通常的非限定名称查找所考虑的范围和名称空间之外,还在其参数的名称空间中查找这些函数名称。
依赖于参数的查找使使用在不同名称空间中定义的运算符成为可能。
在您的示例中a2
,来自名称空间的ns
内容足以使编译器ns
在查找时也要考虑print
。
您的示例有趣的部分是它int_type
也来自ns
,尽管它只是一个typedef,int
没有在中声明ns
。考虑到typedef不会引入新类型(而是别名)。所以a2
确实是一个int
。
PS:这不是特定于Visual Studio。任何符合标准的编译器都应接受发布的代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句