Menu
Home
Create new Paste
Log in
arrayMath
Code
Theme: cobalt
Theme: eclipse
Theme: elegant
Theme: monokai
Theme: neat
Theme: night
Theme: rubyblue
#!/bin/rdmd -unittest import std.stdio; private mixin template _workaround4424() { @disable void opAssign(typeof(this)); } mixin template arrayMath( string DName, ulong DLen, T, VecT ) { mixin( "alias " ~ DName ~ " this;" ); this(this){ mixin( DName ~ " = " ~ DName ~ ".dup;" ); } this()( T[] ext... ) { if( DLen != ext.length ) throw new Exception("bad length"); mixin( DName ~ "[] = ext[];" ); } mixin _workaround4424; auto opAssign(E)( E[] b ) if( is( E : T ) ) { if( DLen != b.length ) throw new Exception("bad length"); foreach( i, ref m; mixin( DName ) ) m = b[i]; return this; } auto opBinary(string op,E)( E[] b ) if( ( op == "+" || op == "-" ) && is( E : T ) ) { if( DLen != b.length ) throw new Exception("bad length"); auto res = VecT(this); foreach( i, ref m; mixin( "res." ~ DName ) ) mixin( "m " ~ op ~ "= b[i];" ); return res; } ref VecT opOpAssign(string op,E)( E[] b ) if( ( op == "+" || op == "-" ) && is( E : T ) ) { this = opBinary!op(b); return this; } } struct vec( string S, T=double ) { alias vec!(S,T) vtype; T[S.length] data; mixin arrayMath!( "data", S.length, T, vtype ); } struct fixvec { real[3] data; mixin arrayMath!( "data", 3, real, fixvec ); } unittest { alias vec!"xyz" vec3; alias vec!"xyzw" vec4; alias vec!("rbg",float) col3; auto a = vec3(0,0,0); a = [1,2,3]; assert( a == [1,2,3] ); auto b = col3(3,2,1); b += a; assert( b == [4,4,4] ); b += [1,1,1]; assert( b == [5,5,5] ); a = [3,2,1]; b = a + b + [1,2,3]; assert( b == [9,9,9] ); auto d = fixvec(4,5,6); b += d; assert( b == [13,14,15] ); auto c = vec4(1,2,3,4); bool exc = false; try{ a += c; } catch( Exception e ) { if( e.msg == "bad length" ) exc = 1; } assert( exc ); } void main() {}
Result:
Success
/
Return code: 0
/
Compilation time:
1.446
seconds
/
Run time:
0.023
seconds
Disassembly
Username
Message
Add comment
Paste info
Author:
Guest
Views:
96
Private:
no
Expires:
Never
Uploaded:
19.10.12 15:06
Votes
:
0
Tweet
Compilation
Compiler:
DMD 2.060
Pointer size:
m64
Actions
Download
Fork
Raw
×
Confirm
Are you sure you want to delete this paste?
There's no way back!
×
Confirm
Reason