if (auto x = cast(C) x)

Q. Schroll via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 9 14:54:46 PDT 2017


For a class/interface type `A` and a class `C` inheriting from 
`A` one can do

   A a = getA();
   if (auto c = cast(C) a)
   { .. use c .. }

to get a `C` view on `a` if it happens to be a `C`-instance.

Sometimes one cannot find a good new name for `c` while there is 
no advantage of accessing `a` when `c` is available. D does not 
allow to shadow `a` in the if-auto declaration for good reasons. 
How about relaxing the rule for cases like these, where the rhs 
is the lhs with a cast to derived?

   if (auto a = cast(C) a)
   { .. use a typed as C .. }

One can think of `a` being *statically* retyped to `C` as this is 
a (strictly) better type information. Internally, it would be a 
shadowing, but it does not matter as the disadvantages don't 
apply (if I didn't miss something).


More information about the Digitalmars-d-learn mailing list