|
Boost : |
From: JOAQUIN LOPEZ MU?Z (joaquin_at_[hidden])
Date: 2008-02-02 07:57:23
----- Mensaje original -----
De: Bruno Lalande <bruno.lalande_at_[hidden]>
Fecha: Sábado, Febrero 2, 2008 12:18 pm
Asunto: [boost] [Boost] Compile-time power of a run-time base
Para: boost_at_[hidden]
> Hello,
>
> I have written for the need of a coworker a function template that
> computesthe compile-time power of a base that is known only at
> runtime. The original
> need was just to avoid having to write things like
> "value*value*value*value*value".
>
> Before doing this, I've been searching for such a thing in the Boost
> documentation and mailing lists, but could only find discussions
> about an
> entierely compile-time version (compile-time exponent of compile-
> time base)
> intended for use in metaprograms. Is there any reason why the
> "semi-compile-time" version I describe here hasn't been discussed?
> Eventhough it can be viewed as a mere syntactic sugar, it can be
> very practical
> when it comes to write by hand a power with a big exponent.
>
>
> In case of interest, here is my code :
>
>
> template <int N>
> struct positive_power
> {
> template <typename T>
> static float result(T base)
> { return base*positive_power<N-1>::result(base); }
> };
I think this is suboptimal: you need only log(N) multiplications
to get positive_power<N>::result(base):
template <int N>
struct positive_power
{
template <typename T>
static float result(T base)
{
float aux=positive_power<N/2>::result(base);
return (N%2)?base*aux*aux:aux*aux;
}
};
HTH,
Joaquín M López Muñoz
Telefónica, Investigación y Desarrollo
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk