Passing a generic struct as parameter

Zardoz luis.panadero at gmail.com
Fri Jul 1 14:46:56 PDT 2011


Finally I try this small test code :

struct A(T, int U) {
	T x;
	static enum foo = U;
	
	Tout opCast( Tout ) () 
	if (isA!Tout)	{
		Tout nt;
		nt.x = x;
		return nt;
	}
	
	string toString() {
		return to!string(x);
	}
}

struct B(T, int I) {
	enum foo2 = I;
	
	alias A!(T, foo2) Internal;
	
	Internal[foo2 * 2] y;
	
	void opIndexAssign(K) (K v, size_t j) 
	if (isA!(K) && K.foo == Internal.foo && is(typeof(K.x) == typeof(y[0].x)) ) {
		y[j] = v;
	}
		
	void opIndexAssign(K) (K v, size_t j) 
	if (isA!(K) && (K.foo != Internal.foo || !is(typeof(K.x) == typeof(y[0].x))) ) {
		y[j] = Internal(v.x);
	}

}

template isA(T) {
  immutable bool isA = __traits(compiles,
        (){  
            T t;
            auto x = t.x;
            auto u = t.foo;     
        }
    );
}


auto bla = A!(int, 2) (10);
auto bla2 =A!(int, 5) (5)
	
B!(int, 3) bleh;
	
bleh[1] = bla;	
bleh[3] = bla2;

writeln(bleh.y);

And write : [0, 10, 0, 5, 0, 0]

So this works. Only I need to discover why when I try it over Vector 
and Matrix class, I get errors...

Finally, I upload to github : git://github.com/Zardoz89/zmath.git
I hope that I not write some barbaric thing in my code.... 
I do all self-learning D

On Fri, 01 Jul 2011 17:19:36 +0200, Simen Kjaeraas wrote:

> On Fri, 01 Jul 2011 08:58:32 +0200, Zardoz <luis.panadero at gmail.com>
> wrote:
> 
>> Well, the problem is that I must do the cast always, see :
>>
>> // alias Matrix!(real,4) Mat4r;
>> // alias Vector!(float, 3) Vec3f;
>> // alias Vector!(real, 4) Vec4r;
>> // In Mat4r, VCol it's aliased to Vector!(real, 4)
>>
>> auto tcol = Mat4r.IDENTITY;
>>
>> auto v = cast(tcol.VCol) Vec3f(1, 2 ,3 ); auto v2 = Vec4r(-1, -2 ,-3
>> ,-4);
>>
>> tcol[1] = v2; // Do a compiler error
>> tcol[2] = v;
> 
> So more likely, this is what you want:
> 
> void opIndexAssign(U)(Vector!(U,dim) v, size_t j) {
>      static if (is(U == T)) {
>          col[j] = v;
>      } else {
>          col[j] = cast(VCol)v;
>      }
> }





-- 
Yep, I'm afraid that I have a blog : zardoz.es


More information about the Digitalmars-d-learn mailing list