I understand a well-known example of creating factorial compilation time calculations using templates, so that recursive runtime calculations are not needed. In this example, all the necessary values โโfor the calculations are known at compile time.
But I looked at this other example of using patterns to calculate the power of a number, and I just donโt understand how this optimization is compared to a similar recursive run-time 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. Thus, at run time, a series of calculations will be performed that will essentially have the same value as m*m*m , right?
Is this a clear advantage for such a template? Maybe I just donโt see it.
source share