Hi, I'm a newbie, hope the attached example works for you.
Peter Alexander wrote:
Since default constructors for structs are not allowed, how do I go
about making all the elements of this Matrix struct default to zero?
(floats default to nan by default).
struct Matrix(int M, int N)
{
float[M][N] elements;
}
Matrix(3, 3) m;
assert(m[0][0] == 0);
?
import std.stdio ;
// directly assign a constant
struct R {
float[3][3] x = [[0.0F, 0.0F, 0.0F],[0.0F, 0.0F, 0.0F],[0.0F, 0.0F,
0.0F]] ;
}
// use template
template ZH(int M, T, T value) {
static if (M == 1)
const T[M] ZH= [value] ;
else
const T[M] ZH= cast(T[M])(ZH!(M - 1, T, value) ~ value) ;
}
template ZV(alias zh, int N) {
static if (N == 1)
const typeof(zh)[N] ZV = [zh];
else
const typeof(zh)[N] ZV = cast(typeof(zh)[N])(ZV!(zh, N - 1) ~
zh) ;
}
template Zero(int M, int N, T, T value) {
const float[M][N] Zero = ZV!(ZH!(M, T, value), N);
}
struct S {
float[4][3] x = Zero!(4,3, float, 0.0F);
}
void main() {
S s ;
R r ;
writefln("%s", s ) ;
writefln("%s", r ) ;
}
// output :
// S([[0 0 0 0] [0 0 0 0] [0 0 0 0]])
// R([[0 0 0] [0 0 0] [0 0 0]])