为什么GCC允许调用这个函数而不首先使用它的命名空间? [英] Why GCC allows calling this function without using its namespace first?
问题描述
Possible Duplicate:
Why does C++ parameter scope affect function lookup within a namespace?
今天我经历了这种奇怪的行为。我可以使用命名空间Strange 调用strangeFn,但不允许调用strangeFn2为什么?
Today I experienced this weird behavior. I can call strangeFn without using namespace Strange
first, but does not allow calling strangeFn2 Why?
namespace Strange
{
struct X
{
};
void strangeFn(X&) {}
void strangeFn2(int) {}
}
int main()
{
Strange::X x;
strangeFn(x); // GCC allows calling this function.
strangeFn2(0); // Error: strangeFn2 is not declared in this scope.
return 0;
}
C ++编译器如何解析符号的范围?
How does C++ compilers resolve the scope of the symbols?
推荐答案
这称为 Argument Dependent Lookup(或Koenig Lookup)
This is called Argument Dependent Lookup (or Koenig Lookup)
基本上,如果一个符号无法解析,
Basically, if a symbol couldn't be resolved, the compiler will look into the namespace(s) of the argument(s).
第二个函数调用失败,因为 strangeFn2
isn' t在当前命名空间中可见,它在参数类型的命名空间中未定义( int
)
The second function call fails, because strangeFn2
isn't visible in the current namespace, neither is it defined in the namespace of it's parameter type (int
)
可以看到这对于操作符函数是否有效:
You can see how this works well with operator functions:
std::complex<double> c, d;
c += d; // wouldn't really work without ADL
或无所不在的iostream运算符:
or the ubiquitous iostream operators:
std::string s("hello world");
std::cout << s << std::endl; // Hello world would not compile without ADL...
有趣的是,这就是hello world看起来像没有ADL (且没有使用
关键字...):
For fun, this is what hello world would look like without ADL (and without using
keyword...):
std::string s("hello world");
std::operator<<(std::cout, s).operator<<(std::endl); // ugly!
在功能模板存在的情况下,有ADL和重载分辨率的阴影角落情况,现在让他们离开答案的范围。
There are shadowy corner cases with ADL and overload resolution in the presence of function templates, but I'll leave them outside the scope of the answer for now.
这篇关于为什么GCC允许调用这个函数而不首先使用它的命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!