dsimcha wrote:
== Quote from Robert Clipsham ([email protected])'s article
dsimcha wrote:
Is there a way to run a class's c'tor on a block of memory from a template
function?  For example:

C newClass(C, CtorArgs...)(CtorArgs args) {
    // Allocate, initialize.
    // Want to call the c'tor that takes type CtorArgs.
}
----
C newClass(C, CtorArgs...)(CtorArgs args) {
     return new C(args);
}
class Foo{ this(int a, string b) { /* do something */ } }
auto foo = newClass!(Foo)(1, "bar");
----
That seems to work here... or are you meaning you already have a block
of memory allocated and want to turn it into an instance of the class?
In which case something like:
----
C newClass(C, CtorArgs...)(CtorArgs args) {
    void* mem;
    // Allocate/initialize etc, store in inst of type C
    // Stolen/adapted from Object.d:
    if( inst.classinfo.flags & 8 && inst.classinfo.defaultConstructor )
    {
        C delegate(CtorArgs) ctor;
        ctor.ptr = cast(void*)inst;
        ctor.funcptr = cast(C function(CtorArgs))
                           inst.classinfo.defaultConstructor;
        return ctor(args);
    }
    return null;
}
----
Should work (untested).

I meant the latter, but not just for the default constructor, for any 
constructor.

I'm not sure that it's possible to access ctors other than the default one, I can't seem to find any mention of them in the abi or object.d, you might have better luck if you search yourself though, I only had a quick skim. If not it might be worth a feature request?

Reply via email to