Equivalents to policy classes in D
Jacob Carlborg
doob at me.com
Tue Apr 3 03:13:58 PDT 2012
On 2012-04-03 01:15, Joseph Rushton Wakeling wrote:
> 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
Maybe you could use template mixins to implement "foo".
mixin template Foo ()
{
void foo () {}
}
class FooBarOne : FooBar
{
mixin Foo;
}
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list