Pure dynamic casts?

Steven Schveighoffer schveiguy at yahoo.com
Tue Sep 22 13:13:14 PDT 2009


On Tue, 22 Sep 2009 16:00:29 -0400, Jarrett Billingsley  
<jarrett.billingsley at gmail.com> wrote:

> On Tue, Sep 22, 2009 at 3:35 PM, Steven Schveighoffer
> <schveiguy at yahoo.com> wrote:
>> On Tue, 22 Sep 2009 14:03:28 -0400, Jarrett Billingsley
>> <jarrett.billingsley at gmail.com> wrote:
>>
>>>
>>> Or you could - I dunno - cache the result of the dynamic cast in a
>>> local, since doing multiple dynamic casts is terrible style anyway.
>>>
>>> Just saying. ;)
>>
>> Yes, this is true of many optimizations :P
>>
>> Are you saying it's bad style because of the expense of dynamic casting  
>> or
>> for some other reason?  If dynamic cast were pure, that takes away that
>> argument.
>
> Dynamic downcasts do usually indicate a weakness in the design. But an
> even more fundamental matter of style is to not repeat yourself. You
> don't use "x + y" if you need the sum of x and y in ten places; you do
> "sum = x + y" and then use "sum." The same applies here. You're not
> just working around a deficiency in the compiler, you're saving
> yourself work later if you need to change all those values, and you're
> giving it some kind of semantic attachment by putting it in a named
> location.

What if x and y are possibly changing in between calls to x + y?

I'm thinking of a situation where o *might* be changing, but also might  
not, the compiler could do some optimization to avoid the dynamic-cast  
calls in the cases where it doesn't change.  These would be hard to code  
manually.  My understanding of pure function benefits (and it's not that  
great) is that you can express yourself how you want and the compiler  
fixes your code to be more optimized knowing it can avoid calls.

> Besides, you're probably going to be doing:
>
> if(auto d = cast(Derived)baseRef)
> {
>     // ..
> }
>
> so you've already bound the result of the dynamic cast to a variable.  
> *shrug*

Probably.  But even then, if this statement is in a loop that might not  
change baseRef, the compiler can avoid dynamic casting again.

-Steve



More information about the Digitalmars-d mailing list