On Wednesday, 27 June 2018 at 12:02:10 UTC, aliak wrote:
This currently fails unless you mark the class as static:

auto construct(T)() {
    return new T;
}
void main() {
    class C {}
    auto s = construct!C;
}

So wondering if there's anything that can be done to get the above working?


Or if there isn't then how could the compiler be enhanced to allow for something like this if possible?

===
The use case is for a non-nullable type, where I want to guarantee that the value inside will never be null. I can't do it for inner classes though. And I can't allow the user to do something like:

void main() {
    class C {}
    auto s = construct(new C);
}

Because I can't guarantee that's not null.


Cheers,
- Ali

After a bit of experimentation

    import std.stdio;
    template construct1(T)
    {
        enum construct1 = "new " ~ T.stringof;
    }

    template construct2(T)
    {
        // Attempt 1
        // can't do this : /
        //alias construct2 = mixin(construct1!T);

        // Attempt 2
        T construct2()
        {
// Error: outer function context of D main is needed to new nested class onlineapp.main.C
            //return new T;

            // Error: undefined identifier C
            //mixin("return new " ~ T.stringof ~ ";");

            return null; // ...
        }
    }

    mixin template construct3(string s, T)
    {
        mixin("auto " ~ s ~ " = new " ~ T.stringof ~ ";");
    }

    void main() {
        class C { int i = 4;}

        auto a = mixin(construct1!C);
        assert(a.i == 4);

        mixin construct3!("b", C);
        b.i = 3;        
        assert(b.i == 3);

        // trying to get around using mixin here...
        auto c = construct2!C;
    }


Can't seem to avoid using mixin in main..

Reply via email to