[Issue 16482] New: Compiler should error on impossible cross-class type casts

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Fri Sep 9 08:27:52 PDT 2016


https://issues.dlang.org/show_bug.cgi?id=16482

          Issue ID: 16482
           Summary: Compiler should error on impossible cross-class type
                    casts
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody at puremagic.com
          Reporter: andrej.mitrovich at gmail.com

The following compiles but it's known at compile-time to return null:

-----
class C { }
class D { }

void main ( )
{
    auto d = new D;
    auto c = cast(C)d;  // compiler knows it will be null
}
-----

It's possible for a class to define opCast, however it's a templated method and
so the compiler would still know if such casts make sense or not:

-----
class C
{
    T opCast(T)() if (is(T == D))
    {
        return new T;
    }
}

class D { }

void main ( )
{
    auto c = new C;
    auto d_from_c = cast(D)c;  // ok, might work

    auto d = new D;
    auto c_from_d = cast(C)d;  // should error
}
-----

There is a slight possibility that this affects some generic code (makes it not
compile), but in such a case the code could easily be changed to use `static if
(is(typeof( cast(Target)source ))).

--


More information about the Digitalmars-d-bugs mailing list