Dynamic and Static Casting

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Thu Feb 10 04:15:49 PST 2011


On Thu, 10 Feb 2011 11:54:02 +0000, Lars T. Kyllingstad wrote:

> On Thu, 10 Feb 2011 16:44:12 +0530, d coder wrote:
> 
>> Greetings All
>> 
>> I have learnt that D has only one casting operator and that is 'cast'.
>> The same operator assumes different functionality depending on the
>> context in which it he being used.
>> 
>> Now I have a situation where I have to downcast an object and I am sure
>> of the objects type and thereby I am sure that the downcast would only
>> be successful. To make the operation faster, in C++ I could have used
>> static_cast operator, thus giving the RTTI a skip. Would this be
>> possible in D? Can I force a static_cast which downcasting?
> 
> Here's one solution.  [...]

Ok, bearophile's solution is better, because it has fewer casts.  I 
forgot you can cast to void*.  So here's an improved version, with some 
template constraints to make sure it's only used for class types:

    T staticCast(T, U)(U obj)  if (is(T == class) && is(U == class))
    {
        return cast(T) cast(void*) obj;
    }

-Lars


More information about the Digitalmars-d-learn mailing list