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).

Reply via email to