Strange alias behaviour in template arguments
Stefan Frijters via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Mar 3 05:42:08 PST 2015
So this is a strange thing I ran into while trying to streamline
some templates in my code, where fixed-length arrays are passed
as runtime arguments. I started out by trying variant fun2(),
which disappointingly didn't work. fun3() then did its job but I
was suspicious and tried fun4() and fun(5), which also worked but
shouldn't. Is this a bug or am I doing something bad?
struct Connectivity(uint _d, uint _q) {
enum d = _d; // Number of dimensions
enum q = _q;
}
alias d2q9 = Connectivity!(2,9);
// Stores fixed-size array of base type T, and the length of the
array is determined by the connectivity.
struct Field(T, alias c) {
alias conn = c;
T[conn.d] payload;
this(in T[conn.d] stuff) {
payload = stuff;
}
}
// Ok
void fun(T)(T field) {
pragma(msg, T);
pragma(msg, T.conn);
pragma(msg, T.conn.d);
pragma(msg, T.conn.q);
}
// cannot deduce function from argument types
void fun2(T)(T field, double[T.conn.d] foo) {
pragma(msg, T);
pragma(msg, T.conn);
pragma(msg, T.conn.d);
pragma(msg, T.conn.q);
field.payload = foo;
}
// Ok!
void fun3(T, alias d = T.conn.d)(T field, double[d] foo) {
pragma(msg, T);
pragma(msg, T.conn);
pragma(msg, T.conn.d);
pragma(msg, T.conn.q);
pragma(msg, typeof(foo)); // 2, okay
field.payload = foo;
}
// Huh?
void fun4(T, alias d = T.conn.q)(T field, double[d] foo) {
pragma(msg, T);
pragma(msg, T.conn);
pragma(msg, T.conn.d);
pragma(msg, T.conn.q);
pragma(msg, typeof(foo)); // expect 9, get 2
field.payload = foo;
}
// Huh?
void fun5(T, alias d = T.conn)(T field, double[d] foo) {
pragma(msg, T);
pragma(msg, T.conn);
pragma(msg, T.conn.d);
pragma(msg, T.conn.q);
pragma(msg, typeof(foo)); // don't know what to expect, still
get 2
field.payload = foo;
}
void main() {
double[d2q9.d] foo;
auto f = Field!(double, d2q9)(foo);
f.fun(); // Sure, this works
// f.fun2(foo); // Won't work without additional alias
f.fun3(foo); // Works, so are we happy?
f.fun4(foo); // No! This isn't supposed to work...
f.fun5(foo); // Nor this...
}
Any thoughts?
More information about the Digitalmars-d-learn
mailing list