Topic: Is upcasting a conversion? -- Conversion operator ambiguity
Author: phalpern@truffle.ultranet.com (Pablo Halpern)
Date: 1996/04/03 Raw View
I want to describe a language issue that may seem perverse conceptually
but which came up in reality when using templates. (I have noticed that
templates bring up many of the degenerate cases in the language). The
problem is best illustrated with the following code:
class x {
public:
x();
operator x() const; // LINE A: conversion from x to x
};
class y : public x
{
};
void main()
{
y Y;
x X = Y; // LINE B: Which conversion? X(X) or y.operator x() ?
}
There are two distinct but related issues here. First, in class x, is it
valid to define an operator that converts an x to an x as in LINE A,
above? The situation comes up in the use of templates as follows:
template <class T>
class Q { public: operator Q<const int>() const; }
If T is const int, then the conversion operator becomes a conversion of
a class to itself. My compiler (Borland 4.02) doesn't mind this and the
code works as intended (converting any Q<T> to a Q<const int>). I think
this is good, so I hope it is, in fact legal according to the DWP.
It would seem that a conversion operator x::operator x() would never be
used since there is never a need to convert from an object to itself.
The problem comes in when inheritence and upcasting are involved, as in
LINE B, above. In this case, my compiler complains of an ambiguity
between "x::operator x() const" and "x::x(const x&)". It is interesting
to note that if I change the declaration of X to "x X(Y)" the compiler
does not complain, so there is definately a bug in the compiler. The
question is, what is the bug? Should the compiler complain about an
ambiguity or not?
My questions, therefore, are as follows:
Is it valid to define an operator to convert x to x?
Is upcasting from a derived class to a base class considered a
conversion, equal in precidence to user-defined conversions?
Can user-defined conversions ever override built-in conversions (e.g.
from x to const x, from derived to base, from x to x&, etc.)?
If there is a real ambiguity, is there another way I can get my
template class to work without running a foul of it?
-------------------------------------------------------------
Pablo Halpern phalpern@truffle.ultranet.com
I am self-employed. Therefore, my opinions *do* represent
those of my employer.
---
[ comp.std.c++ is moderated. To submit articles: try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
[ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu ]