Equivalents to policy classes in D

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Mon Apr 2 16:15:41 PDT 2012


Hello all,

I'm coming to D from a background programming in C and C++, though I wouldn't 
describe myself as an expert in either.

One of the C++ techniques I picked up over the last couple of years was the use 
of policy classes, and I'm wondering how D addresses this issue of combining 
various small components together to implement a given interface.

D's interfaces seem an obvious starting point, but from the documentation I've 
read, it seems like each implementation has to be written separately.  So, if I 
have an interface,

   interface FooBar {
     void foo();
     void bar();
   }

... I can of course write two different implementations,

   class FooBarOne : FooBar {
     override void foo() {
       // Foo function implementation
       ...
     }
     override void bar() {
       // Bar function implementation
       ...
     }
   }

   class FooBarTwo : FooBar {
     override void foo() {
       // Foo function implementation
       ...
     }
     override void bar() {
       // Bar function implementation
       ...
     }
   }

... but suppose that I'd like the foo() function to be identical in both; how do 
I avoid rewriting the code?

In C++ I'd think of a policy class,

   template <class Foo, class Bar>
   class FooBar : public Foo, public Bar {
     ...
   };

and then have,

   typedef FooBar<FooGeneric,BarOne> FooBarOne;

   typedef FooBar<FooGeneric,BarTwo> FooBarTwo;

... but I don't see how to do something equivalent with D's interfaces and 
implementations.  Can anyone advise?

Thanks and best wishes,

     -- Joe


More information about the Digitalmars-d-learn mailing list