When authoring a library in a particular namespace, it's often convenient to provide overloaded operators for the classes in that namespace. It seems (at least with g++) that the overloaded operators can be implemented either in the library's namespace:
namespace Lib { class A { }; A operator+(const A&, const A&); } // namespace Lib
or the global namespace
namespace Lib { class A { }; } // namespace Lib Lib::A operator+(const Lib::A&, const Lib::A&);
From my testing, they both seem to work fine. Is there any practical difference between these two options? Is either approach better?
Overview. A namespace-scoped operator watches and manages resources in a single Namespace, whereas a cluster-scoped operator watches and manages resources cluster-wide. An operator should be cluster-scoped if it watches resources that can be created in any Namespace.
In C++, we can change the way operators work for user-defined types like objects and structures. This is known as operator overloading. For example, Suppose we have created three objects c1 , c2 and result from a class named Complex that represents complex numbers.
You should define them in the library namespace. The compiler will find them anyway through argument dependant lookup.
No need to pollute the global namespace.
Putting it into the library namespace works because of Koenig lookup.
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