static opCall not working?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 19 06:25:36 PDT 2015


On 07/19/2015 03:26 AM, TC wrote:
> I tested the code from: http://dlang.org/struct.html
> Section: Dynamic Initialization of Structs
>
>
> 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
>
> which does not compile (Error: cannot implicitly convert expression (3)
> of type int to S).
>
> What is wrong here? Docs or behavior? Tested it on asm.dlang.org where
> it fails with all compiler versions.

The docs are not clear: s and t are not meant to be module-scope 
variables, which should be initialized in a 'static this()' (or 'shared 
static this()'). Put them inside a function like main() and it works fine.

Ali



More information about the Digitalmars-d-learn mailing list