no property 'opCall' for type ... what am I doing wrong?
Chad J
gamerChad at _spamIsBad_gmail.com
Fri May 4 22:28:11 PDT 2007
Daniel Keep wrote:
>
> Chad J wrote:
>
>>Myron Alexander wrote:
>>
>>>Chad J wrote:
>>>
>>>
>>>>main.d:
>>>>import std.stdio;
>>>>
>>>>struct A
>>>>{
>>>> int member1;
>>>>}
>>>>
>>>>struct B
>>>>{
>>>> int member2;
>>>>}
>>>>
>>>>void main()
>>>>{
>>>> A a;
>>>> writefln( (cast(B)a).member2 );
>>>>}
>>>>
>>>>That code results in the following compiletime errors:
>>>>main.d(16): Error: no property 'opCall' for type 'B'
>>>>main.d(16): Error: function expected before (), not 1 of type int
>>>>main.d(16): Error: no property 'member2' for type 'int'
>>>>
>>>>I am using DMD 1.014 on Windows.
>>>>This seemed to work at some point in history, but not anymore. What
>>>>am I doing wrong?
>>>>
>>>>Thanks
>>>
>>>
>>>Chad,
>>>
>>>What you are doing there is illegal code. The structs A and B are
>>>distinct types and cannot be cast to each other. If it worked in the
>>>past, then it was probably a compiler bug.
>>>
>>>Since structs do not allow for inheritance (they are value types),
>>>then the only way would be to use classes and inheritance or templates.
>>>
>>>What are you trying to achieve? Perhaps I can try to suggest a
>>>different method.
>>>
>>>Regards,
>>>
>>>Myron.
>>
>>Ah, makes sense. I figured out what I was doing wrong in the original
>>code. Thanks.
>
>
> This works:
>
> void main()
> {
> A a;
> writefln( (cast(B*)&a).member2 );
> }
>
> Just keep in mind that you can't take the address of a function
> argument, so if you do this inside a function, you have to make a copy
> first. I've used this trick to do all sorts of evil things like turn a
> structure into a ubyte[] :P
>
> -- Daniel
>
Yeah I like that trick. I didn't know about the copying function
arguments catch though, good to know.
I suppose I was also used to being able to cast structs into other
structs, sort of like how you can cast numeric types into other numeric
types, and generalizing it to being able to cast any value type into
another value type. Guess it doesn't hold though. I can always use
this dereference-address trick to get around it.
More information about the Digitalmars-d-learn
mailing list