On Sunday, 4 October 2015 at 20:18:25 UTC, rsw0x wrote:
On Sunday, 4 October 2015 at 18:02:21 UTC, bitwise wrote:
Currently, it seems like someone will eventually take all these classes/hierarchies and flatten them into some struct/template approach. I am not looking forward to this at all. I like polymorphism when it's appropriate.

It's just a symptom of D classes being so difficult to use without the GC, compared to when I first picked up D to now I find myself barely *ever* using classes and just C-style(er, D-style?) polymorphism with structs, mixins, and alias this.
Bye.

You can use classes without GC _and_ with deteministic lifetime:

----
import std.stdio;

class A {
        string name;
        
        this(string name) {
                this.name = name;
        }
        
        void hello() {
                writeln("Hallo, ", this.name);
        }
}

struct Scoped(T) if (is(T == class)) {
        import core.stdc.stdlib : malloc, free;
        
        enum SIZE = __traits(classInstanceSize, T);
        
        T obj;
        
        this(Args...)(auto ref Args args) {
                void[] buffer = malloc(SIZE)[0 .. SIZE];
                buffer[] = typeid(T).init[];
                
                this.obj = cast(T) buffer.ptr;
                this.obj.__ctor(args);
        }
        
        ~this() {
                destroy(this.obj);
                free(cast(void*) this.obj);
        }
        
        alias obj this;
}

auto scoped(T, Args...)(auto ref Args args) if (is(T == class)) {
        return Scoped!T(args);
}

void main() {
        auto a = scoped!A("Foo");
        a.hello();
}
----

Reply via email to