At compile time

Jarrett Billingsley jarrett.billingsley at gmail.com
Tue Aug 4 17:24:46 PDT 2009


On Tue, Aug 4, 2009 at 7:57 PM, bearophile<bearophileHUGS at lycos.com> 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;
> }
>
>
> 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?

I don't think you can call struct methods at compile-time.  Kind of
lame, I know.  Try making norm a free function.

> Can the D2 compiler modified/improved to allow this?

It sure would be nice.


More information about the Digitalmars-d-learn mailing list