This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: FWD: How to reuse a friend operator?


Piotr Wyderski wrote:
Hello,

below is a repost from comp.lang.c++. The problem is how
to use a friend operator defined inside a class by another
friend operator in this class. Which compiler is right?


Victor Bazarov wrote:



The code compiles fine with Comeau C++.


But consider this one, which is a simplified version of my problem:


-----------8<-------------


#include <iostream>


class X {


public:

int v;

int operator +(const int R) {

            return 3;
        }

friend inline int operator +(const int L, const X& R) {

            std::cout << "OK int";
            return L;
        }

friend inline int operator +(const char L, const X& R) {

            std::cout << "OK char";
            return operator +(static_cast<int>(L),R); // (*)
        }
};

int main(int argc, char *argv[]) {

    X x;
    'a'+x;
 return 0;
}


-----------8<-------------


Desired behaviour is that the program displays "OK charOK int"

GPP 3.4 displays:

test.cpp: In function `int operator+(char, const X&)':
test.cpp:24: error: no matching function for call to `X::operator+(int,
const X&)'
test.cpp:10: note: candidates are: int X::operator+(int)

If I change the (*) line to

return ::operator +(static_cast<int>(L),R);

then it works. VC7.1 in all cases reports an error:
g++ 3.4 is correct.

[3.4.1]/9 gives the lookup rules for friends defined in a class. It says
that lookup shall proceed as described for lookup in member function
definitions.  So in operator+(const char, const X&); we look in X first and
find X::operator+(int);

nathan

--
Nathan Sidwell    ::   http://www.codesourcery.com   ::     CodeSourcery LLC
nathan@codesourcery.com    ::     http://www.planetfall.pwp.blueyonder.co.uk



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]