Learn template by math vector class

Darren (dgrant at kerberos-productions dot com) Darren_member at pathlink.com
Wed Jun 21 22:57:51 PDT 2006


I am learning about D template details by implementing a static sized vector
class.  Opinions on this code (like how to solve the obvious errors) or
alternatives that would be better practice in D would be appreciated:

class vector( T, size_t size )
{
private:
T p[ size ];

public:
this()
{
}

this( T[] q )
in
{
assert( q.length > 0 );
}
body
{
foreach ( size_t i, T v; q )
{
p[ i ] = v;
}
}

T opIndex( size_t i ) 
in
{
assert( i >= 0 && i < size );
}
body
{
return p[ i ]; 
}

T opIndexassign( T v, size_t i ) 
in
{
assert( i >= 0 && i < size );
}
body
{
p[ i ] = v;
return p[ i ]; 
}

T x() { return p[ 0 ]; }
T y() { return p[ 1 ]; }
T z() { return p[ 2 ]; }
T w() { return p[ 3 ]; }

void x( T v ) { p[ 0 ] = v; }
void y( T v ) { p[ 1 ] = v; }
void z( T v ) { p[ 2 ] = v; }
void w( T v ) { p[ 3 ] = v; }
}


example:
vector!( float, 2 ) 2d_vector;

So the obvious problem is that upon instantiation in the example, z and w
attributes implicitly generate array bounds errors.  Is there a form of generic
specification in D that can be applied to solve this?





More information about the Digitalmars-d-learn mailing list