Wrapping an arbitrary class/struct API

Artur Skawina art.08.09 at gmail.com
Sat Aug 24 06:47:10 PDT 2013


On 08/24/13 15:14, Joseph Rushton Wakeling wrote:
> Hello all,
> 
> (This accidentally got posted as a reply to someone else's thread -- I'm reposting in order to make sure that thread doesn't get diverted.)
> 
> Suppose that I have a struct like e.g.:
> 
>     struct A
>     {
>         void foo(int n) { ... }
>         void foo(Range)(Range r) { ... }
>         int bar() { ... }
>         int bar(double x) { ... }
>         // ... and others ...
>     }
> 
> ... an I want to wrap it in another struct, B.  If I do this manually it would be something like,
> 
>     struct B
>     {
>         private A a;
>         void foo(int n) { return a.foo(n); }
>         void foo(Range)(Range r) { return a.foo(r); }
>         // ... etc ...
>     }
> 
> But suppose that I don't a priori know the list of functions (and function arguments) that need to be wrapped.  How could I go about working this out, with a generic programming approach, i.e. _without_ manually writing the individual cases?

   struct B
   {
      private A a;

      auto ref opDispatch(string M, A...)(A args) {
         return mixin("a."~M~"(args)");
      }
   }

This will handle the simple case you described; the opDispatch
template will get more complex once it needs to forward other
stuff, like fields and properties, or handle ref args properly etc.

> More specifically, how could I work this out limited to a specific function of A (say, foo) ... ?

Template constraint.

artur


More information about the Digitalmars-d-learn mailing list