Static cast

BCS ao at pathlink.com
Wed Jun 25 16:17:12 PDT 2008


Reply to Jason,

> &BCS Wrote:
> 
>> Reply to Jason,
>> 
>>> What is the proper way to implement static cast?
>>> 
>>> cast(T) to shift with an object/ interface hierarchy is dynamic and
>>> slow. My problem is that cast(T)cast(void*) does not honor vtable
>>> locations and ClassInfo is only available at runtime.
>>> 
> ;
> 
>> up cast or down cast?
>> 
> Both. Upcasting to an interface shows up in my profiler.
> 
>> IIRC upcast /is/ non-dynamic and skipping the test on downcast is
>> just a bad idea.
>> 
> I've implemented algorithms to operate on interfaces. Operations
> called by the algorithm require casting. All the data operated on by
> an algorithm is the same type. In this case, it's safe and will speed
> up execution by at least 15%
> 

I'm not sure there /is/ a way to do non dynamic casts to/from interfaces. 
For one thing an interface reference does not reference the same address 
as the object.

interface I {}
class C : I {}
C c = new C;
assert(cast(void*) c != (cast(void*)cast(I) c);  // not actually tested

If you have a slew of casts from/to the _exact_same_types_ to do, you might 
cast the first one, find the pointer difference, and then just add that for 
the rest of the casts. But if any of your assumptions are off, your toast.




More information about the Digitalmars-d-learn mailing list