Equivalents to policy classes in D

Cristi Cobzarenco cristi.cobzarenco at gmail.com
Mon Apr 2 17:24:37 PDT 2012


Mixins templates would be the answer:
import std.exception;

mixin template UncheckedIndices( T ) {
  ref T opIndex( int i ) {
    return this.get_( i );
  }

}

mixin template CheckedIndices( T ) {
  ref T opIndex( int i ) {
    enforce( i > 0 && i < this.size );
    return this.get_( i );
  }
}

struct Array( T, alias IndexPolicy ) {
  private T* array;
  private int size_;

  this( size_t n ) {
    array = (new T[ n ]).ptr;
  }

  @property size_t size() {
     return size_;
  }

  private ref T get_( size_t i ) {
    return array[ i ];
  }

 mixin IndexPolicy!T;
}

void main() {
 auto arr1 = Array!(int, UncheckedIndices)( 10 );
auto arr2 = Array!(int, CheckedIndices)( 10 );
 arr2[ 11 ] = 5;
}




---
Cristi Cobzarenco
BSc in Artificial Intelligence and Computer Science
University of Edinburgh
Profile: http://www.google.com/profiles/cristi.cobzarenco



On 3 April 2012 00:15, Joseph Rushton Wakeling <joseph.wakeling at webdrake.net
> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20120403/a6587344/attachment.html>


More information about the Digitalmars-d-learn mailing list