Consider a Factory that creates instances of various different resource object instances, all of which have a common interface, and returns a handle to them.

class Factory
{
   struct Handle{}

   Handle create(R: Resource, ARGS...)(ARGS args)
   {
      auto r = new R(args);
      //...
      return handle;
    }
}

auto f = new Factory;
auto wallpaperhandle = f.create!Bitmap(...);


In order to be able do something with these resources there's a function to get the resource instance from a handle:

   auto get(R: Resource)(Handle h) {...};

auto bitmap = f.get!Bitmap(wallpaperhandle);
auto size = bitmap.getSize();
if (condition)
   bitmap.scaleByFactor(2);

I don't like this approach because it exposes the instance directly.
What I want instead is something like this

auto size = f.dispatch!(Bitmap, Bitmap.getSize)(wallpaperhandle);
if (condition)
   f.dispatch!(Bitmap, Bitmap.scaleByFactor)(wallpaperhandle, 2);

Implement this for free functions i would do something like this

void dispatch(alias fn, ARGS...)(Handle handle, ARGS args)
{
   fn(handle, args);
}


but how can I call fn in the context of an object instance?

class Factory {
auto ref dispatch(R: Resource, alias fn, ARGS ...)(Handle handle, ARGS args)
  {
     auto r = get!R(handle);
     assert(stuff is valid);

return r.fn(args); // How can I call class function 'fn' using r ?
  }
}

mixin(something) comes to mind, but are there better options ?

Reply via email to