Default constructor for structs
bearophile
bearophileHUGS at lycos.com
Sat Aug 7 07:44:40 PDT 2010
Peter Alexander:
> 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).
This doesn't work, I don't know why:
float[M][N] elements = 0.0;
A bad looking solution:
struct Matrix(int M, int N) {
float[M][N] elements;
static Matrix opCall() {
Matrix m;
foreach (ref row; m.elements)
row[] = 0.0;
return m;
}
}
void main() {
auto m = Matrix!(3, 3)();
assert(m.elements[0][0] == 0);
}
A possible solution avoids going against the language (the default nan value for FP values isn't there for show, it's there because it improves your code):
struct Matrix(int M, int N) {
float[M][N] elements;
this(float init=0) {
foreach (ref row; elements)
row[] = init;
}
}
void main() {
auto m = Matrix!(3, 3)(0.0);
assert(m.elements[0][0] == 0);
}
This doesn't work:
struct Matrix(int M, int N) {
float[M][N] elements;
this(float init=0.0) {
foreach (ref row; elements)
row[] = init;
}
}
void main() {
auto m = Matrix!(3, 3)();
assert(m.elements[0][0] == 0);
}
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list