Reputation: 76386
I have a class that is in top-level namespace for historical reasons. I need to define a function for it that must1 be found using argument-dependent lookup. Is the top-level namespace considered associated namespace of such class or do I have to make some workaround?
1Otherwise the template that uses it might not find it, because symbols defined after the template are only seen when found by ADL.
Upvotes: 1
Views: 111
Reputation: 3841
Here is my take on the standard:
From [basic.lookup.argdep] (2):
— If T is a class type (including unions), its associated classes are: the class itself; the class of which it is a member, if any; and its direct and indirect base classes. Its associated namespaces are the innermost enclosing namespaces of its associated classes.
From [basic.namespace] (2) (and 3.3.6 where global namespace
is defined):
The outermost declarative region of a translation unit is a namespace; see 3.3.6.
So I don't see anything to exclude the global namespace from ADL.
Upvotes: 1
Reputation: 171177
The global namespace is not special in this regard, it works just like any other namespace and is thus perfectly fine for your use case.
Live example 1 of global namespace working.
Live example 2 of ADL actually being the reason #1 works1.
Here's the text of the live example:
#include <iostream>
struct X {};
template <class T>
void bar(T t)
{
foo(t);
}
void foo(X x)
{
std::cout << "Foo\n";
}
int main()
{
X x;
bar(x);
}
1 This fails, because ADL cannot find the function, while normal lookup would. So it proves that #1 really works thanks to ADL.
Upvotes: 2