At compile time
bearophile
bearophileHUGS at lycos.com
Tue Aug 4 16:57:19 PDT 2009
D2 is now able to execute math functions (sin, cos, sqrt, etc) at compile time.
This little C++ program compiles correctly with G++:
// C++ code
#include <math.h>
#include <stdio.h>
struct V3 {
double x, y, z;
V3(const double a, const double b, const double c) : x(a), y(b), z(c) {}
V3 operator*(const double d) const { return V3(x * d, y * d, z * d); }
V3 norm() const { return *this * (1.0 / sqrt(magsqr())); }
double dot(const V3 &v) const { return x * v.x+y * v.y + z * v.z; }
double magsqr() const { return dot(*this); }
};
const V3 v(V3(-0.5, -0.65, 0.9).norm());
int main() {
printf("%f %f %f\n", v.x, v.y, v.z);
return 0;
}
But similar D2 program produces, with DMD v.2.031:
test.d(12): Error: non-constant expression (V3(1,2,3)).norm()
// D2 code
import std.math, std.c.stdio;
struct V3 {
double x, y, z;
V3 opMul(double d) { return V3(x * d, y * d, z * d); }
V3 norm() { return this * (1.0 / sqrt(this.magsqr())); }
double dot(ref V3 v) { return x * v.x+y * v.y + z * v.z; }
double magsqr() { return dot(this); }
}
const V3 v = V3(1.0, 2.0, 3.0).norm();
int main() {
printf("%f %f %f\n", v.x, v.y, v.z);
return 0;
}
Do you know why?
Can the D2 compiler modified/improved to allow this?
Bye and thank you,
bearophile
More information about the Digitalmars-d-learn
mailing list