Why GCC allows calling this function without using

2019-01-17 16:03发布

Possible Duplicate:
Why does C++ parameter scope affect function lookup within a namespace?

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;
}

How does C++ compilers resolve the scope of the symbols?

1条回答
神经病院院长
2楼-- · 2019-01-17 16:40

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).

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

or the ubiquitous iostream operators:

 std::string s("hello world");
 std::cout << s << std::endl; // Hello world would not compile without 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!

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.

查看更多
登录 后发表回答