Operator overloading, structs

Don nospam at nospam.com
Tue Jun 9 18:50:20 PDT 2009


Leandro Lucarella wrote:
> Don, el 10 de junio a las 02:02 me escribiste:
>> bearophile wrote:
>>> Leandro Lucarella:
>>>> I think the more general solution is to allow multiple implicit cast
>>>> operators and simply provide implicit conversion to bool for the classes
>>>> you want to be able to do if (x) on.
>> No, it's not more general.
> 
> *it is* more general, that's exactly what you don't like about it =)

If you consider "also introduces bugs" as "more general"... I just call 
that "wrong" <g>.

> 
>> You do NOT want to allow conversion to bool.  The reason is that bool
>> can itself be implicitly converted, eg this compiles:
>>
>>    bool b = true;
>>    int y = b;
>>
>> --
>> And that's a disaster:
>>
>> struct Foo
>> {
>>   bool opImplicitCast() { return true; }
>> }
>>
>> Foo x;
>> if (x) { ... }  // OK
>> int y = x;      // This would compile!!!!
>>
>> C++ libraries go to a fair bit of trouble to allow if(x) without
>> allowing x to be converted to bool.
> 
> I don't think is a *disaster*, but I agree that maybe the distintion can
> be useful (I didn't though about that). 

It's very important. If you allow implicit conversion to bool, all kinds 
of garbage will compile. You might as well abandon static typing.

That makes me think, why not to
> disable implicit cast from bool to int? It's even defined what the value
> of int x = true; should be?
Yes. It's 1.

 > I guess there are plenty of cases where you
> don't want that, but I can't think of anything now...

I can't think of any case where it's a good idea. (It's required in D1 
because opEquals() stupidly returns int).
But that still leaves the problem:

bool b = x; // doesn't compile if x is a class, or an array, or an AA.
But it would compile if x is a struct with implicit conversion to bool.

> Of course, int to bool implicit cast should still be possible.

No. It isn't legal now! Only the special case of literals 0 and 1. Which 
is perfect.

The only time when you want to allow an implicit conversion to bool is 
when you have some kind of "smart bool" struct which is supposed to be a 
drop-in replacement for "bool". It's quite distinct from
if(x) --> if(x!=0).

The strength of my proposal is that it would allow existing code to 
"just work" without modification. You wouldn't have to think about it.
To argue against it, find a situation where it would be a problem.



More information about the Digitalmars-d mailing list