if (auto x = cast(C) x)

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 9 20:41:30 PDT 2017


On Wednesday, 9 August 2017 at 21:54:46 UTC, Q. Schroll wrote:
> 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).

One option is to use 
https://dlang.org/library/std/algorithm/comparison/cast_switch.html


More information about the Digitalmars-d-learn mailing list