Proposal: Implicit type conversion for structs
Jaak
jpdt at telkomsa.net
Fri Oct 27 03:46:09 PDT 2006
One could possibly require that the shortest conversion chain is always
used, and it is an error if a conversion is required and more than one
conversion chains of the same length exists.
In your example below A and B are implicitly compatible by two possible
chains of conversions:
B => int => C
B => C => A
This could be flagged as ambigious. Making the compatibility explicit
would remove the error.
In the below example:
Add to class A a conversion from B:
A &operator =(const B &);
Add to class B a conversion to B:
operator A() const;
Its a tradeoff: no need for preference ordering, at the cost of having
to define extra conversion functions.
The shortest conversion chain is then simply: B => A
Kristian wrote:
> On Thu, 26 Oct 2006 06:15:11 +0300, Jaak <jpdt at telkomsa.net> wrote:
>> Bill Baxter wrote:
> [snip]
>>> That said, the proposal sounds reminiscent of C++'s overloadable
>>> (implicit) conversion operators, which have caused me more trouble
>>> than benefit. E.g.
>>> operator float() const { return aFloat; }
>
>
> Hmm, I have to say that the both sides have good points. Implicit type
> casting can cause trouble. But in the other hand, it can be also very
> useful in some situations, i.e. when the types are indeed compatible.
>
> In C++ I have had problems with signed/unsigned type casting. I can't
> just now recall what they were, but they were annoying, and the compiler
> should have got them right.
I've been bitten by that in D as well:
if (array.length-5>0) // is always true as length property is unsigned
But this is luckily not a mistake one keeps on making.
>
> I think implicit type conversion can be made a lot safer (than it's in
> C++ and in any other language I know of). It would require type
> concersion rules. That is, more than simply telling the compiler that
> here are all the conversion operators, use them as you wish.
>
> For example, in C++:
>
> class C;
>
> class A {
> A &operator =(int);
> A &operator =(const C &);
> };
>
> class B {
> operator int() const;
> operator C() const;
> };
>
> void func() {
> A a;
> B b;
>
> a = b;
> }
>
> Should 'b' to converted to 'int' or 'C'? There is no way of knowing that..
>
> However, if one could define that 'C' is prefered over 'int', there
> would be no problems.
> For example, the order in which the operator are defined would tell the
> preference order (or you could use some kind of numeric value, etc):
>
> class B {
> operator C() const; //1.
> operator int() const; //2.
> };
>
> There could be some other rules as well. I mean, human can always tell
> that what conversion should be used, if possible. Why not tell that to
> compiler also?
>
> Is it possible to create such rules in compact way that would apply
> (almost) all the cases? Is the preference ordering enough?
More information about the Digitalmars-d
mailing list