I understand the well-known example of creating a compile-time factorial calculation with templates such that recursive runtime calculations are not necessary. In such an example, all the required values for the calculations are known at compile time.
But I ran across this other example for using templates to calculate the power of a number, and I just don't get how this is an optimization over a similar runtime recursive function:
template<int n>
inline int power(const int& m) { return power<n-1>(m)*m;}
template<>
inline int power<1>(const int& m) { return m;}
template<>
inline int power<0>(const int& m) { return 1;}
cout << power<3>(m)<<endl;
Obviously, m
cannot be known at compile time in this example. So at run time, a series of calculations will still be performed that result in essentially the same thing as m*m*m
, right?
Is their a clear advantage to a template like this? Perhaps I am just not seeing it.
You can get the advantage of template metaprogramming only if you know the X
and Y
both at compile time. The example code:
template<unsigned int X, unsigned int N>
struct Power { static const unsigned int value = X * Power<X,N-1>::value; };
template<unsigned int X>
struct Power<X,0> { static const unsigned int value = 1; };
Usage: Power<X,Y>::value
to determine the X^Y
.
Demo.
In your posted code (which happens to use template
s but not meta-programming!), only the Y
is known at compile time and X
is passed as runtime parameter. Which means the result also will be calculated at runtime and we have to rely on compiler based optimizations. Better to use std::pow(..)
in such cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With