For elegance, encapsulation and to exploit ADL (Argument Dependent Lookup) is common to define a function inside the namespace of the function argument.
Suppose I have two libraries in different namespace. There are three cases 1) one is part of a library I control and the other is third party (for example Boost), or 2) I control both, or 3) I control none (just writing "glue" code).
I have something like this,
namespace ns_A{
struct A{...}; // something that looks like iostream
}
namespace ns_B{
struct B{...};
}
I want to "stream" B in to A, what is the best option
namespace ???{ // what is more correct ns_A, or ns_B?
A& operator<<(A& a, B const& b){...}
}
or should I put it in both namespaces?
namespace ns_B{
A& operator<<(A& a, B const& b){...}
}
namespace ns_A{
using ns_B::operator<<;
}
Which is the best namespace to define a binary function like this?
(Does C++11's namespace inline change any recommendation?)
(I use the example operator<<
because, other things being equal it seems intuitively be better to prefer namespace ns_B
.)
EDIT: this is the most complete guide and reference I could find on real use of namespaces https://www.google.com/amp/s/akrzemi1.wordpress.com/2016/01/16/a-customizable-framework/amp/