The type to cast from. The programmer must ensure it is legal to make this cast.
1 // Regular cast, which has been verified to be legal by the programmer: 2 { 3 long x; 4 auto y = cast(int) x; 5 } 6 7 // However this will still compile if 'x' is changed to be a pointer: 8 { 9 long* x; 10 auto y = cast(int) x; 11 } 12 13 // castFrom provides a more reliable alternative to casting: 14 { 15 long x; 16 auto y = castFrom!long.to!int(x); 17 } 18 19 // Changing the type of 'x' will now issue a compiler error, 20 // allowing bad casts to be caught before it's too late: 21 { 22 long* x; 23 static assert( 24 !__traits(compiles, castFrom!long.to!int(x)) 25 ); 26 27 // if cast is still needed, must be changed to: 28 auto y = castFrom!(long*).to!int(x); 29 }
A wrapper on top of the built-in cast operator that allows one to restrict casting of the original type of the value.
A common issue with using a raw cast is that it may silently continue to compile even if the value's type has changed during refactoring, which breaks the initial assumption about the cast.