templatizing parameters and induction (was Re: Writing Bug-Free C/D Code)

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Thu Mar 22 23:28:23 PDT 2007


Reiner Pope wrote:
> Andrei Alexandrescu (See Website For Email) wrote:
[snip]
> Is this in contrast to the
> 
>     int foo(const int x)(const int x, int y, int z);
> 
> syntax you mentioned earlier? If so, then I am very grateful you now 
> support the much cleaner syntax you now do.

Yes. The cleaned-up syntax was Dave's idea.

> However, while I don't dispute that this is useful, aren't there also 
> times when you want the compiler to do that implicitly? (Maybe the 
> compiler already does, or there are plans to do so in the future, in 
> which case you can ignore the below. If the compiler already does, 
> though, I think this should be documented)

I don't know. Right now I don't think so. The whole point of overloading 
is to write "intelligent" custom code that implements the given 
semantics in various ways. I don't think the compiler can generally do 
that with today's technology.

> Often, the compiler can optimize the function just through 
> const-folding, without needing the coder to write all the overloads. 
> However, const-folding across function calls doesn't seem to be done in 
> DMD unless the function is inlined.

And I think that's good. You don't want to send the compiler for a wild 
goose chase so that it runs 100 times slower.

> Consider the example everyone gives with partial eval:
> 
> double pow(long exponent, double base)
> {
>     if (exponent < 0) return pow(-exponent, base);
>     if (exponent%2 == 0)
>     {
>         auto val = pow(exponent/2, base);
>         return val * val;
>     }
>     else
>     {
>         return base * pow(exponent-1, base);
>     }
> }
> 
> Suppose this is too big to be inlined by DMD. Do you then have to write 
> an identical overload for a statically-known exponent?
> 
> double pow(static long exponent, double base)
> {
>     ... // A duplicate of the above code
> }

I'm afraid so. The compiler can't read your mind and figure that it 
would be good to fold. If such code is frequent enough, probably we'll 
provide a way to avoid source duplication. (Btw you got the parameter 
order backwards.)

> I suppose you could allow templating by staticness, but even that is 
> still wrong. If the compiler sees a function call with *some* 
> statically-known parameters, shouldn't it automatically create a 
> template and see how much it can const-fold. If nothing, scrap the 
> template and go back to the old version.
> 
> Having to actually write the overload seems like an optimization as 
> stupid as having to write 'inline' or 'register'.

That's for the future. One step at a time. The technology is not there 
yet, and compile times still matter. Don't forget that in 1970 
"register" and in 1980 "inline" were ideas of much practical value.


Andrei



More information about the Digitalmars-d mailing list