opCall example

Extrawurst spam at extrawurst.org
Wed Jan 30 03:00:00 PST 2008



Ary Borenszweig schrieb:
> Saaa escribió:
>> What does different exactly mean in this example?
>> I read that s is of type S thus should be calling opCall (S v), but 
>> it doesn't.
>>
>> If opCall is overridden for the struct, and the struct is initialized 
>> with a value that is of a different type, then the opCall operator is 
>> called:
>>
>> struct S{   int a;
>>
>>     static S opCall(int v)
>>     {    S s;
>>     s.a = v;
>>     return s;
>>     }
>>
>>     static S opCall(S v)
>>     {    S s;
>>     s.a = v.a + 1;
>>     return s;
>>     }
>> }
>>
>> S s = 3;    // sets s.a to 3
>> S t = s;    // sets t.a to 3, S.opCall(s) is not called
>
> opCall is used like this:
>
> S s = S(3);
> S t = S(s);
>
> I don't know why your first statement works. I think it's because S is 
> just a wrapper for an int, so an int can be implicitly casted to S.

the first statement works cause he created an opCall for S to be called 
with just an int. the second statement doesn't call S opCall(S) cause a 
struct assign expression just performs a memory copy when S t = s; to 
have the second opCall called u would have to write what Ary suggested: 
S t = S(s);

~Extrawurst


More information about the Digitalmars-d-learn mailing list