A
alephhepe
An error message from gcc leads me to this question:
Can an operator be overloaded for a class template as both a member
function and a friend template function?
In the following code, I declare operator+ to be both a member
function (for int) and a friend template function (for C<T>):
////////////////////////////////////////////////////////////
// Forward declarations
template<typename T> struct C;
template<typename T> C<T> operator+(C<T> self, C<T> that);
// Template with operator+ as both a member and friend
template<typename T>
struct C {
C<T> operator+(int) { return C<T>(); }
friend C<T> operator+ <>(C<T> self, C<T> that);
// Above line gives an error: "declaration of operator+ as non-
function"
};
template<typename T>
C<T> operator+(C<T> self, C<T> that) { return C<T>(); }
int main() {
C<char> a, b, c=a+b, d=a+0;
}
////////////////////////////////////////////////////////////
Is this supposed to be legal? Maybe it's a parse error in gcc?
(Oddly enough, if I put the friend declaration first, I don't get the
error message.)
Can an operator be overloaded for a class template as both a member
function and a friend template function?
In the following code, I declare operator+ to be both a member
function (for int) and a friend template function (for C<T>):
////////////////////////////////////////////////////////////
// Forward declarations
template<typename T> struct C;
template<typename T> C<T> operator+(C<T> self, C<T> that);
// Template with operator+ as both a member and friend
template<typename T>
struct C {
C<T> operator+(int) { return C<T>(); }
friend C<T> operator+ <>(C<T> self, C<T> that);
// Above line gives an error: "declaration of operator+ as non-
function"
};
template<typename T>
C<T> operator+(C<T> self, C<T> that) { return C<T>(); }
int main() {
C<char> a, b, c=a+b, d=a+0;
}
////////////////////////////////////////////////////////////
Is this supposed to be legal? Maybe it's a parse error in gcc?
(Oddly enough, if I put the friend declaration first, I don't get the
error message.)