Boost logo

Boost :

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


Hello,

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
"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? 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)
{
        return
        power_if_positive
        <
                N,
                boost::mpl::greater_equal
                <
                        boost::mpl::int_<N>,
                        boost::mpl::int_<0>
>::type::value
>::result(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 :

power<3>(myValue);
power<0>(myValue);
power<-5>(myValue);

Thanks
Bruno


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk