Pattern operators apparently disagree with ambiguity

This is not a duplicate. I checked a lot of answers, FAQ and more. None of this told me the news. Here is the simplified code. This is the minimum to get and explain the error.

/*** Polynomial.hpp ********************************************************/ namespace Modulus { // Forward declaration of the types and non-inline template friend functions. template <typename T> class Polynomial; template <typename T> Polynomial<T> operator + (Polynomial<T> const & p, Polynomial<T> const & q); } namespace Modulus { template <typename T> class Polynomial { public: Polynomial() { } // [!] when you comment this in, you get the error. //Polynomial operator + () const { return *this; } friend Polynomial operator + <> (Polynomial const & p, Polynomial const & q); }; } // namespace // Template: include .cpp file. //#include "Polynomial.cpp" ///^ It is commented out, for compiling in one file. /*** Polynomial.cpp ********************************************************/ namespace Modulus { template <typename T> Polynomial<T> operator + (Polynomial<T> const & p, Polynomial<T> const & q) { return Polynomial<T>(); } } // namespace /*** main.cpp **************************************************************/ //#include "Polynomial.hpp" using namespace Modulus; int main() { Polynomial<int> p; p + p; return 0; } 

When I comment out a line under [!] In, the error I get is friends can only be classes or functions (Clang ++) or declaration of 'operator+' as non-function (g ++).

For me, it seems that compilers mistakenly accept two statements. As far as I learned that the operator overloads the material, unary and binary operators are completely independent and can be unambiguously different in the number of arguments .

So why is the error occurring? Creating a unary operator by a friend using standard practice makes the code compiled in both compilers.

+6
source share
1 answer

When you declare something in scope, it hides the decartation with the same name in any wider scope. Here the declaration of the operator+ member hides the non-member declaration. Thus, the friend declaration refers to the member, and not to the non-member, hence the error.

You will need to qualify the name if you want to refer to both in the same area:

 Polynomial operator + () const { return *this; } friend Polynomial Modulus::operator + <> (Polynomial const & p, Polynomial const & q); ^^^^^^^^^ 
+4
source

Source: https://habr.com/ru/post/984358/


All Articles