On 3 April 2012 12:24, Cristi Cobzarenco <cristi.cobzare...@gmail.com> wrote:
> 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;
> }

Another option is to use alias this to forward method calls on.
Currently you can only have 1 alias this in a class/struct, but that
is a temporary and D is supposed to allow multiple alias this
declarations.

Depending on the scope of your situation, you could also use
conditional compilation in conjunction with templates to implement
your policies, often interfaces aren't needed when you only want/need
a minor change, I only use them for polymorphism in D.

--
James Miller

Reply via email to