egcs-1.0.1 confused by explicit cast
Adam P. Jenkins
ajenkins@cs.umass.edu
Wed Feb 4 18:50:00 GMT 1998
> >>>>> Richard Hadsell writes:
>
> > Jason Merrill wrote:
> >>
> >> The problem is that an explicit cast is treated as an explicit constructor
> >> call, not a conversion. g++ is correct.
>
> > Sorry, I can't accept that. Please confirm your interpretation with the
> > standard.
>
> 5.2.9 Static cast [expr.static.cast]
>
> 2 An expression e can be explicitly converted to a type T using a
> static_cast of the form static_cast(e) if the declaration T t(e);"
> is well-formed, for some invented temporary variable t (_dcl.init_).
> The effect of such an explicit conversion is the same as performing
> the declaration and initialization and then using the temporary vari-
> able as the result of the conversion.
>
> Since the above declaration is a direct-initialization, and so the
> candidates are the constructors of T, the same is true of a cast. The cast
> notation does not have different semantics.
The only way the above clause could be interpreted as saying that "an
explicit cast is treated as an explicit constructor call, not a
conversion", even when the class has a user-defined conversion
function, is if you are not aware that C++ has user-defined conversion
functions. If they don't get called even when an explicit cast is
used, then what are they even in the language for?
Look at section 12.3, which describes class conversions:
-------------------------------------------------------------------------
12.3 Conversions [class.conv]
1 Type conversions of class objects can be specified by constructors and
by conversion functions. These conversions are called user-defined
conversions and are used for implicit type conversions (_conv_), for
initialization (_dcl.init_), and for explicit type conversions
(_expr.cast_, _expr.static.cast_).
-------------------------------------------------------------------------
The above _explicitly_ says that user-defined conversion functions
should be called for explicit type conversions. So unless this has
changed since the November '96 working paper, I'd have to say you're
wrong. If what you're saying were true, then the following program
would not be legal, since int has no constructor which accepts an A.
class A {
public:
operator int() { return 1; }
};
int main()
{
A a;
int i = (int)a; // calls A::operator int(), not int::int(A&)
i = int(a); // again, calls A::operator int()
i = a; // and yet again...
return i;
}
This program is legal, and in fact compiles with egcs, because the
conversion operator calls the conversion function, not a constructor
of int. Now, if int had a constructor that accepted an A, then there
could be ambiguity between calling "A::operator int()" and
"int::int(A&)", but that wasn't the problem in the original post of
this thread.
Adam
More information about the Gcc-bugs
mailing list