Boost logo

Boost :

From: John Moeller (fishcorn_at_[hidden])
Date: 2008-05-22 15:39:29


Bruno Lalande <bruno.lalande <at> gmail.com> writes:

> Yep it's a possibility. It's close to my last attempt, using the MPL:
>
> template <int N>
> struct even_positive_power
> {
> template <typename T>
> static typename tools::promote_args<T>::type result(T base)
> {
> return positive_power<2>::result(
> positive_power<N/2>::result(base));
> }
> };
>
> template <int N>
> struct odd_positive_power
> {
> template <typename T>
> static typename tools::promote_args<T>::type result(T base)
> {
> return base*positive_power<2>::result(
> positive_power<N/2>::result(base));
> }
> };
>
> template <int N>
> struct positive_power
> {
> template <typename T>
> static typename tools::promote_args<T>::type result(T base)
> {
> return
> mpl::if_<
> mpl::greater_equal<mpl::int_<N%2>, mpl::int_<1> >,
> odd_positive_power<N>,
> even_positive_power<N>
> >::type::result(base);
> }
> };

Bruno,

I think that you'll need a specialization for positive_power<1> *and*
positive_power<2> with this. In fact, both of these otherwise generate a 4-
deep infinitely-recursive function call at runtime. Starting at
positive_power<2>:

positive_power<2>::result
  even_positive_power<2>::result
    positive_power<1>::result
      odd_positive_power<1>::result
        positive_power<2>::result

Starting at positive_power<1> yields the same result. Specializing only
positive_power<1> will still cause an infinite recursion in positive_power<2>:

positive_power<2>::result
  even_positive_power<2>::result
    positive_power<1>::result
    positive_power<2>::result

Note that these won't be infinite *template* generations, but infinite
*runtime* calls.

One more thing. The argument is passed by value, which is ok for builtins.
Will all those potentially excess temporaries be an issue for larger UDTs?
Perhaps the argument type of result() should be wrapped so that it's a const
reference if it's larger than a pointer.

John M.


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