www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Casting Structs

reply "Paul D Anderson" <claude.rains msn.com> writes:
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, 

     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 

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?

Jun 01 2014
parent Philippe Sigaud via Digitalmars-d <digitalmars-d puremagic.com> writes:
At the very least, it's contradicted by the website:


"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