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.
Bolpat source share