Summary: A static down cast in Phobos
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Keywords: patch
          Severity: enhancement
          Priority: P2
         Component: Phobos

--- Comment #0 from 2011-02-10 12:34:45 PST ---
D2 lacks the static_cast of C++. It's an unsafe operation, but now and then
someone asks for it, for spots where performance is critical.

With Lars T. Kyllingstad I've written a staticDownCast(). Something similar may
be added to Phobos:

import std.stdio, std.traits, std.typetuple;

/// C++ static_cast for just down-casting
T staticDownCast(T, F)(F from) if (is(F == class) &&
                                   is(T == class) &&
                                   staticIndexOf!(F, BaseClassesTuple!T) != -1)
    in {
        assert((from is null) || cast(T)from !is null);
    } body {
        return cast(T)cast(void*)from;

// some demo code

class Foo {}
class Bar : Foo {}
class Spam {}

Bar test1() {
    Foo f = new Foo;
    Bar b = cast(Bar)f;
    return b;

Bar test2() {
    Foo f = new Foo;
    Bar b = staticDownCast!Bar(f);
    return b;

void main() {
    Spam s = new Spam;
    Bar b = staticDownCast!Bar(s); // compile-time error

Asm produced by DMD 2.051 with -O -release -inline that shows it avoids the
dynamic cast:

_D4test5test1FZC4test3Bar   comdat
L0:     push    EAX
        mov EAX,offset FLAT:_D4test3Bar7__ClassZ
        mov ECX,offset FLAT:_D4test3Foo7__ClassZ
        push    EAX
        push    ECX
        call    near ptr __d_newclass
        add ESP,4
        push    EAX
        call    near ptr __d_dynamic_cast
        add ESP,8
        pop ECX

_D4test5test2FZC4test3Bar   comdat
L0:     push    EAX
        mov EAX,offset FLAT:_D4test3Foo7__ClassZ
        push    EAX
        call    near ptr __d_newclass
        add ESP,4
        pop ECX

Configure issuemail:
------- You are receiving this mail because: -------

Reply via email to