At compile time

Sergey Gromov snake.scaly at gmail.com
Wed Aug 5 17:15:38 PDT 2009


Tue, 04 Aug 2009 19:57:19 -0400, bearophile wrote:

> D2 is now able to execute math functions (sin, cos, sqrt, etc) at compile time.
> 
> [snip]
> 
> 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;
> }

You can't call methods at compile time, and you can't pass temporary by
reference.  This works:

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); }
}

V3 mul(ref V3 v, double d) {
    return V3(v.x*d, v.y*d, v.z*d);
}

V3 norm(V3 v) {
    return mul(v, 1.0 / sqrt(magsqr(v)));
}

double dot(ref V3 a, ref V3 b) {
    return a.x*b.x + a.y*b.y + a.z*b.z;
}

double magsqr(ref V3 v) {
    return dot(v, v);
}

const V3 v = norm(V3(1.0, 2.0, 3.0));

int main() {
    printf("%f %f %f\n", v.x, v.y, v.z);
    return 0;
}


More information about the Digitalmars-d-learn mailing list