Topic: Conversion question
Author: smeyers@netcom.com (Scott Meyers)
Date: 1995/07/29 Raw View
I know the committee has tinkered with the argument matching rules since
publication of the ARM, and compilers disagree on the following program
(see below), so I'm asking the net for its wisdom on what should happen
in the following program. Only one line is interesting, the one with
the comment.
#include <iostream.h>
class charProxy {
private:
char ch;
public:
charProxy(char& c) : ch(c) {}
operator char() const { cout << "Calling operator char\n"; return ch; }
operator char&() { cout << "Calling operator char&\n"; return ch; }
};
void swap(char& a, char& b) { char temp = a; a = b; b = temp; }
int main()
{
char x = 'x';
char y = 'y';
charProxy xp = x;
charProxy yp = y;
swap(x, y);
swap(xp, yp); // should invoke operator char& twice?
return 0;
}
On the line with the comment, a conversion is necessary for each parameter,
and the conversion to char can't be called, because that would require
binding a temporary to a non-const reference parameter. The only remaining
conversion operator is to char&, but does the DWP state that conversion to
char& directly is better than conversion to char and from there to char&?
Borland 4.51 calls operator char, which is just wrong. MetaWare 3.31
complains of ambiguity. g++ 2.6.3 calls operator char&. I'm told that
Symantec agrees with Borland, and Watcom and Metroworks agree with MetaWare.
I'd like to know what the "correct" behavior is as defined by the
current draft standard. If you think you know what should happen,
please chime in, citing the DWP to bolster your interpretation.
Thanks,
Scott