This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Problems with binary member and friend operator in template class
- From: Georg Hager <georg dot hager at rrze dot uni-erlangen dot de>
- To: gcc-help at gnu dot org
- Date: Mon, 30 Jan 2006 13:14:39 +0100
- Subject: Problems with binary member and friend operator in template class
Hi all,
g++ 4.0.3 reports an error when compiling the following C++
source. The problem appears when I declare a binary operator (here
operator+) once as a member and once as a friend with the class type
as second parameter:
----------------------------------------------
#include <iostream>
using namespace std;
template <class T> class P;
template <class T> P<T> operator+(T,const P<T>&);
template <class T>
class P{
private:
T d;
public:
explicit P(int i=0);
P<T> operator+(T);
friend P<T> operator+<>(T,const P<T>&); // line 15
};
template <class T>
P<T>::P(int i) : d(i) {}
template <class T>
P<T> P<T>::operator+(T x)
{
return P<T>(x*d);
}
template <class T> P<T> operator+(T x,const P<T>& p)
{
return P<T>(x*p.d);
}
int main()
{
P<int> p(4),q,r;
q=3+p;
r=p+3;
return 0;
}
----------------------------------------------
The error is:
opp.cc:15: error: declaration of 'operator+' as non-function
opp.cc:15: error: expected ';' before '<' token
opp.cc: In function 'P<T> operator+(T, const P<T>&) [with T = int]':
opp.cc:35: instantiated from here
opp.cc:11: error: 'int P<int>::d' is private
opp.cc:29: error: within this context
This might be my misunderstanding the C++ standard, but I
strongly suspect it's a compiler bug. I have to add the following
observations:
- the code compiles if, everything else being equal,
the class is not a template
- the code compiles if the member operator* and the
friend declarations are interchanged
Thanks for any help,
Georg.