Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces and Operator Overloading in C++

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?

like image 777
jonner Avatar asked Oct 05 '08 11:10

jonner


People also ask

What is a namespace of the operator?

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.

What is operator overloading and example?

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.


2 Answers

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.

like image 94
David Pierre Avatar answered Sep 28 '22 11:09

David Pierre


Putting it into the library namespace works because of Koenig lookup.

like image 33
Ferruccio Avatar answered Sep 28 '22 12:09

Ferruccio