Static argument optimization

Steven Schveighoffer schveiguy at yahoo.com
Mon Oct 6 16:29:07 PDT 2008


"Vladimir Panteleev" wrote
> Hello,
>
> Often I encounter cases where I have a function taking some arguments, and 
> I'd like for the compiler to generate separate code for the function when 
> some of the arguments are known at compile time. For example, consider 
> this function:
>
> int pow(int n, int power)
> {
> return power==0 ? 1 : n*pow(n, power-1);
> }
>
> I am looking for a way to make the function work at runtime, while pow(n, 
> 3) to be inlined as n*n*n, and pow(2, 3) to be precalculated as 8. Is it 
> possible to do this with some template trickery without having to write 
> three versions of the function? I know macros should be able to do this in 
> theory...

pow(2,3) should be pre-executed as you wish, due to CTFE rules.

Not sure about optimizing pow(n, 3) though.  Pure functions with tail 
recursion should help though when they are implemented.

BTW, you can optimize your function slightly for times when neither argument 
is pre-known:

int pow(int n, int power)
{
   if(power == 0) return 1;
   if(power & 1) return n * pow(n, power - 1);
   auto tmp = pow(n, power / 2)
   return tmp * tmp;
}

-Steve 





More information about the Digitalmars-d mailing list