Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

call function without namespace, is it a feature or a bug?

namespace ns {
    void f() {}

    struct Foo {};
    void foof(Foo) {};
}
int main() {
    // f(); // cannot find f
    foof(ns::Foo{}); // call to ns::foof(Foo)
}

I found we can leave out namespace when calling a function with type defined in the same namespace.
I didn’t find this rule in cppreference namespace. Is it a feature or a compiler bug?

I tried several gcc and clang compiler and they all work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Is it a feature or a compiler bug?

It’s a c++ feature called Argument Dependant Lookup, or ADL.

From cppreference:

Argument-dependent lookup, also known as ADL, or Koenig lookup 1, is
the set of rules for looking up the unqualified function names in
function-call expressions, including implicit function calls to
overloaded operators. These function names are looked up in the
namespaces of their arguments in addition to the scopes and namespaces
considered by the usual unqualified name lookup.

In your case since you specified the namespace for the Foo argument, the compiler was able to lookup the function foof in the same namespace.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading