digitalmars.D.learn - templates
- ddos (50/50) Jul 17 2014 for example and learning purpose i want to create an arithmetic
- bearophile (6/21) Jul 17 2014 You can add a template constraint and write two functions:
for example and learning purpose i want to create an arithmetic vector class. for a vector of arbitrary size i defined my opBinary like this: class TVector(T,int n) { T[n] val; ..... TVector opBinary(string op)(TVector rhs) { auto tmp = zip(val[],rhs.val[]).map!("a[0]"~op~"a[1]")().array; T[n] v = tmp[]; return new TVector!(T,n)(v); } } now assume i do often need TVector!(T,4) in my program, and i want to optimize this implementation, is it possible to write a specialized implementation for methods of TVectors with the specific template parameters? e.g.: (not working) class TVector!(T,4) { TVector4!(T) opBinary(string op)(TVector4!(T) rhs) { static if (op == "+") { return new TVector4!T( [val[0]+rhs.val[0], val[1]+rhs.val[1], val[2]+rhs.val[2], val[3]+rhs.val[3]]); } else static assert(0, "Operator "~op~" not implemented"); } } one possible solution would be a static if, like this: TVector opBinary(string op)(TVector rhs) { static if(n == 4) { // fast impl for n==4 } else { // old impl } } but i'd like to avoid this since it makes the code very ugly to read any suggestions :) ? thx for your help, greetings from vienna, austria :)
Jul 17 2014
ddos:one possible solution would be a static if, like this: TVector opBinary(string op)(TVector rhs) { static if(n == 4) { // fast impl for n==4 } else { // old impl } } but i'd like to avoid this since it makes the code very ugly to read any suggestions :) ?You can add a template constraint and write two functions: TVector opBinary(string op)(TVector rhs) if(n == 4) {... TVector opBinary(string op)(TVector rhs) if(n != 4) {...} Bye, bearophile
Jul 17 2014