Why is operator overloading like this in D?

Daniel Keep daniel.keep+lists at gmail.com
Sat Dec 9 22:29:24 PST 2006


CloudiDust wrote:
> Greetings everybody, I am a novice in the D world (as well as one in a
> newsgroup), come from the realm of C++. As I am so used to the operator
> overloading mechanism in C++, it's strange enough for me that the D way
> differs in a few aspects, as follows:

Welcome :)

> 1. The cast operator can have only one overloaded version.
> 
> Is it a way to force the programmers not to rely on type cast?

Pretty much.  For example, if you use cast(int)(some_float), then you 
have no control over what sort of cast: does it round (and if so, in 
what direction), or does it just truncate?

The way to do this in D is to use a toType() function.

> 2. There is nothing like "opPreInc".
> 
> In the reference, I got the point that "Since ++e is defined to be
> semantically equivalent to (e += 1), the expression ++e is rewritten as (e +=
> 1) ...", so what if I only intend to overload the ++e, not the += operator,
> just like the way STL defined its input / forward iterators?

I think this has been done to prevent people from playing semantic 
silly-buggers with operators, like how C++ overloaded "+" to mean 
"concatenation" with strings.

This way, ++ always means "+= 1".  You have a reasonable expectation 
that operators do what you would expect them to.  At the very least, 
"ptr.next" is self-explanatory, whilst "++ptr" isn't as much :3

> 3. On the missing of "opAssign".
> 
> Mr.Bright (I suppose :) stressed that we do not need to overload the
> assignment operator to do anything other than a bit copy. So if one struct
> contains pointers or references to others, we are hit. Maybe I am so immersed
> in the C++ way that I feel the way like java / C# is slightly misleading.
> Could you give me some advice on how to "overcome" that?

Don't forget that because D is garbage collected, in the most cases, you 
don't need to do anything special if you have pointers.  The GC will 
take care of things for you.

If you really *do* need to copy the data a structure is pointing to, my 
suggestion would be to implement "dup" member functions.  It's a little 
inconvenient, but it means that you can always count on "=" just doing a 
bit copy, and not something more.

So "a = b" means "do a bit copy of b", and "a = b.dup" means "duplicate 
b in entirety".  Plus, if you need to control how deep the copy does, 
you can use an argument.

> BTW: I wonder if the scoped objects are still references, as they are "newed"?

Not really sure.  I'll have to disassemble some code to check... :)

> Many thanks for your time,
>   ~CloudiDust

No problem, hope this helped and enjoy your stay.

	-- Daniel



More information about the Digitalmars-d-learn mailing list