Question

File A.hpp:

struct foo
{
   int x;
} foo;

inline bool operator ==(const foo &lhs, const foo &rhs)
{
   /* ... */
}

File B.hpp

#include "A.hpp"

namespace SomeNamespace
{
   bool operator==(const foo &lhs, const foo &rhs)
   {
      /* ... */
   }

   /* ... */
   void someFunction(const foo &foo_instance1, const foo &foo_instance2)
   {
      CPPUNIT_ASSERT(foo_instance1 == foo_instance2);
   }
}

The compiler error for the line with the ASSERT is:

error: ambiguous overload for 'operator==' ...

So, the problem is that the compiler sees both comparison operators.

The definition in the global namespace of A.hpp and the definition in the SomeNamespace of B.hpp are ambiguous.

Why does the compiler not use the defintion in the SomeNamespace?

Était-ce utile?

La solution

You've defined the same function twice; what do you expect to happen? The compiler finds SomeNamespace::operator== with unqualified name lookup, and ::operator== with ADL. Since both have exactly the same signature, there is no way for the compiler to choose one over the other.

As a general rule, overloaded operators for a type should be defined in the same namespace as the type, and no where else. (If the overloaded operator takes two different types, defined in two different namespaces, I'd put the operator in the global namespace. But such cases are rare.)

Autres conseils

In your program operator== is defined in Global namespace and Somenamespace.

So when you are trying to access the operator== then compiler is unable to resolve which function to call, as both functions have same signature ans both are visible to compiler.

So to use operator== defined in SomeNamespace you must use SomeNamespace::operator== and for the operator define in Global namespace you must use ::operator==.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top