digitalmars.D - Casting Structs
- Paul D Anderson (17/17) Jun 01 2014 This has been discussed on the learning forum but I wanted to
- Philippe Sigaud via Digitalmars-d (19/19) Jun 01 2014 At the very least, it's contradicted by the website:
This has been discussed on the learning forum but I wanted to
bring this to a wider audience.
Apparently structs can be cast to other structs as long as
they're the same size. In my case I have a decimal struct which
is parameterized with the precision, max exponent, rounding mode,
etc.:
struct Decimal!(99,999,Rounding.HALF_EVEN)
can be cast to
struct Decimal!(16,259,Rounding.FLOOR)
without explicitly overriding the opCast function.
Timon Gehr showed an example of this for non-parameterized
structs,also.
My question is is this expected behavior? If so, does this affect
constness? Or type safety?
Using this certainly makes my life easier but is this a feature
or is it a bug that will be disallowed at some point?
Paul
Jun 01 2014
At the very least, it's contradicted by the website: http://dlang.org/expression#CastExpression "Casting a value v to a struct S, when value is not a struct of the same type, is equivalent to: S(v)" In your case, you have no 'this' in Decimal to accept a Decimal with other arguments. This should not work. Timon provides a nice example: struct A{ int a,b; } struct B{ long x; } void main(){ auto a=A(); auto b=cast(B)a; } Here, cast(B)a should be transformed into B(a). AFAICT, this should not compile, but it does.
Jun 01 2014








Philippe Sigaud via Digitalmars-d <digitalmars-d puremagic.com>