Vectors and matrices in D

mario pernici mario.pernici at mi.infn.it
Tue Mar 13 02:55:30 PDT 2007


Artyom Shalkhakov Wrote

> struct Vec3 {
>     float opIndex( int index ) {
>         assert( index >= 0 && index < 3 );
>         return ( &x )[index];
>     }
> 
>     void opIndexAssign( float f, int index ) {
>         assert( index >= 0 && index < 3 );
>         ( &x )[index] = f;
>     }
> 
>     Vec3 opAddAssign( inout Vec3 v ) {
>         x += v.x;
>         y += v.y;
>         z += v.z;
> 
>         return *this;
>     }
> /*
>     // on C++
>     Vec3 &operator+=( const Vec3 &v ) {
>         x += v.x;
>         y += v.y;
>         z += v.z;
> 
>         return *this;
>     }
> */
> 
>     float x, y, z;
> }
> 
> struct Mat3 {
>     // I think that copying is costly here..
>     Vec3 opIndex( int index ) {
>         return rows[index];
>     }
> /*
>     // this is how it looked like on C++
>     Vec3 &operator[]( const int index ) {
>         assert( index >= 0 && index < 3 );
>         return rows[index];
>     }
>     const Vec3 &operator( const int index ) {
>         assert( index >= 0 && index < 3 );
>         return rows[index];
>     }
> */
> 
>     void opIndexAssign( Vec3 v, int index ) {
>         rows[index] = v;
>     }
> 
>     private Vec3 rows[3];
> }
> 
> unittest {
>     Mat3   m;
> 
>     m[0][0] = 1.0f;
>     assert( m[0][0] == 1.0f );
>     // The above assertion fails all the time.

Thsi works, though I am not sure it answers your question.

struct Mat3 {
    float opIndex(size_t i, size_t j) {
        return rows[i][j];
    }

    void opIndexAssign(float v, size_t i, size_t j ) {
        rows[i][j] = v;
    }

    private Vec3 rows[3];
}


Mario


More information about the Digitalmars-d-learn mailing list