template functions, a special case of constant folding?
Hasan Aljudy
hasan.aljudy at gmail.com
Thu Mar 23 15:35:47 PST 2006
Sorry, should've gone to the D section!!
Hasan Aljudy wrote:
> Given the following expression:
> #x = 10 * 5 + y;
> the compiler will compute 10 * 5 at compile-time and convert the
> expression into
> #x = 50 + y;
>
> I think that's called constant-folding, am I right?
>
> Why can't this be extended such that for the following function:
> # int add( int x, int y ) { return x + y; }
>
> if it's called with constant arguments:
> # x = add( 10, 3 );
>
> the compiler shall do the computation at compile time and convert it to:
> # x = 13;
> is there a particular reason for not doing that?
>
> What I'm trying to say is, why do we need templates to do compile-time
> computation of square roots? (as shown on
> http://www.digitalmars.com/d/templates-revisited.html)
>
> Why not, instead of calling the templated sqrt
> # x = sqrt!(2);
> you just call the regular sqrt
> # x = sqrt(2);
> and the compiler, if smart enough, should do the computation at compile
> time?
>
> If it's too hard to make the compiler smart enough, then maybe we can
> add a keyword to hint to the compiler that if all arguments to this
> function are constants then it can be "folded"!
> After all, that's essentially what the "template" keyword is doing!
> (kinda, not really though, I know).
>
> # fold int add( int x, int y ) { return x + y; }
> vs.
> # template add( int x, int y ) { const add = x + y; }
>
> The "fold" version of the function can be reused for non-constant
> arguments. Where as the templated version can't. (although I'm not
> entirely sure about that).
>
>
>
>
>
More information about the Digitalmars-d
mailing list