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/
In case 1, it is easy: put it in the namespace
that you control.
In case 2, it's up to your choice: whatever appears more logical. In your example case, I would prefer ns_B
.
The only tricky situation is 3. You shouldn't really add to either namespace
. If you want the new 'glue' functionality as part of your own third namespace mine
, then naturally put it in there and any use of that functionality within mine
will be automatically resolved. Naturally, this will not envoke ADL, but there is no need for it, since all you want is to use the new functionality within mine
, not somewhere else.
You can put your operator in either namespace and it will work. As a best practice, put it in the namespace that belongs to your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With