templates
ddos via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jul 17 13:35:26 PDT 2014
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 :)
More information about the Digitalmars-d-learn
mailing list