Boost logo

Boost :

From: Bruno Lalande (bruno.lalande_at_[hidden])
Date: 2008-02-02 05:28:42


I have written for the need of a coworker a function template that computes
the compile-time power of a base that is known only at runtime. The original
need was just to avoid having to write things like

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? Even
though 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); }

template <>
struct positive_power<0>
        template <typename T>
        static float result(T)
        { return 1; }

template <int N, bool>
struct power_if_positive
        template <typename T>
        static float result(T base)
        { return positive_power<N>::result(base); }

template <int N>
struct power_if_positive<N, false>
        template <typename T>
        static float result(T base)
        { return 1/positive_power<-N>::result(base); }

template <int N, typename T>
float power(T base)

It supports positive, null and negative integer exponents. Some improvements
can surely be done, like allowing to specify the desired return type.

Examples of use :



Boost list run by bdawes at, gregod at, cpdaniel at, john at