At compile time
div0
div0 at users.sourceforge.net
Wed Aug 5 12:35:24 PDT 2009
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
bearophile wrote:
> 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;
> }
<snip>
> Do you know why?
> Can the D2 compiler modified/improved to allow this?
>
> Bye and thank you,
> bearophile
Not really relevant to the compile time issue but, your d2 code should be:
import std.math;
import std.stdio;
struct V3 {
double x, y, z;
this(double _x, double _y, double _z) {
x = _x;
y = _y;
z = _z;
}
V3 opMul(double d) const { return V3(x * d, y * d, z * d); }
V3 norm() const { return this * (1.0 / sqrt(this.magsqr())); }
double dot(ref V3 v) const { return x * v.x+y * v.y + z * v.z; }
double magsqr() const { return dot(this); }
}
const V3 v;
static this() {
v = V3(1.0, 2.0, 3.0).norm();
}
int main() {
writefln("%f %f %f", v.x, v.y, v.z);
writefln("%f", v.magsqr());
return 0;
}
This produces identical behavior to the c++ example.
As Jarrett said, in c++ you have hidden runtime initialisation,
which is made explicit in D.
Having it work at compile time would be sweet.
- --
My enormous talent is exceeded only by my outrageous laziness.
http://www.ssTk.co.uk
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
iD8DBQFKed78T9LetA9XoXwRApwgAJ9Ut0GNbpDndlv5hbqFrGI0sT8PfwCgq2YQ
C/C4nKF1U8ybh/nI4TBNqZk=
=coIo
-----END PGP SIGNATURE-----
More information about the Digitalmars-d-learn
mailing list