c++ - template operators fail seemingly on ambiguity -


this not duplicate. i've checked lots of answers, faq , else. nothing of told me news. here simplified code. it's minimum , explain error.

/*** polynomial.hpp ********************************************************/  namespace modulus { // forward declaration of types , 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 comment in, error.     //polynomial      operator +      () const { return *this; }      friend polynomial operator + <> (polynomial const & p,                                      polynomial const & q); };  } // namespace  // template: include .cpp file.    //#include "polynomial.cpp" ///^ commented out, compiling in 1 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 comment line under [!] in, error friends can classes or functions (clang++) or declaration of ‘operator+’ non-function (g++).

for me, seems compilers mistake 2 operators. far i've learned operator overloading stuff, unary , binary operators independent , can uniquely distinguished number of arguments.

so why error occur? making unary operator friend using standard practice, makes code compile fine on both compilers.

when declare in scope, hides delcarations of same name in wider scope. here, declaration of member operator+ hides of non-member. friend declaration refers member, not non-member, hence error.

you'll need qualify name if want refer both in same scope:

polynomial      operator +      () const { return *this; }  friend polynomial modulus::operator + <> (polynomial const & p, polynomial const & q);                   ^^^^^^^^^ 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -