On 12.03.2010 23:03, Walter Bright wrote:
BCS wrote:
Random thought: Aside from making a new corner case, why not make
static constructors in mixins only depend on imports from where they
are defined rather than where they are used?


Template mixins are intended to behave like macros - they are
instantiated in the context of where they are used, not where they are
defined.

Regular templates are instantiated in the context of where they are
defined, not used.

But then:

module a;

static this() {} // 1

template Foo(int i)
{
    static this() // 2
    {
    }
}
----

module b;
import a;

static this() // 3
{
}

alias Foo!(1) foo;
----

Currently the construction order is 1, 3, 2 instead of the expected 1, 2, 3. In other words, the constructor in the template instance (2) should be combined with constructor 1, not 3.

If static constructors in templates ran during the initialization of the module where they are defined, the problem with mixed-in code could be solved like this:

module a;

template StaticCtor(alias ctor)
{
    static this()
    {
        ctor();
    }
}

mixin template Foo(int i)
{
    void construct() { writeln("Constructing for ", i); }
    alias StaticCtor!(construct) ctor;
}

----
module b;

import a;
import c;

mixin Foo!(1);

----
module c;

import a;
import b;

mixin Foo!(2);

So, though Foo is mixed into modules 'b' and 'c', its instances would be constructed in module 'a' via the regular StaticCtor template.

Still a hack but the code at least makes it quite explicit for maintainers to stay alert.




Reply via email to