Dec 6, 2013 at 1:21am UTC
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
template < typename T, T b, unsigned int e >
struct pow : std::integral_constant< decltype (b*1), b * pow<T,b,e-1>::value > {} ;
template < typename T, T b >
struct pow<T,b,0> : std::integral_constant< decltype (b*1), T(1) > {} ;
int main()
{
std::cout << pow< char , 'd' , 3 >::value << '\n' ;
}
http://ideone.com/oU9MRg
Last edited on Dec 6, 2013 at 1:23am UTC
Dec 6, 2013 at 1:29am UTC
Ah, I feel kind of silly for that now. Thankyou!
Though, shouldn't line 7 use (decltype(b*1))(1) instead of T(1) ?
Last edited on Dec 6, 2013 at 1:31am UTC
Dec 6, 2013 at 1:41am UTC
> Though, shouldn't line 7 use (decltype(b*1))(1) instead of T(1)
decltype(b*1) is the type after integral promotion (if any) has been applied; T(1) would be promoted if required.
ie. in std::integral_constant< int, char('a') > , the char is promoted.
Dec 6, 2013 at 3:53am UTC
Yes, I was trying to do it with templates ;)
Dec 6, 2013 at 2:13pm UTC
note that your template approach has O(n) recursion depth, so you can't go too far. As with much of template metaprogramming, it benefits from divide-and-conquer style O(log n) recursion depth solutions, for example see
static_pow
in this post
http://stackoverflow.com/a/19831565/273767 (which also demonstrates a TMP n'th root!)
Last edited on Dec 6, 2013 at 2:14pm UTC
Dec 6, 2013 at 5:17pm UTC
> As with much of template metaprogramming, it benefits from divide-and-conquer style
> O(log n) recursion depth solutions
Yes, thanks Cubbi.
In this paricular case (class template), it doesn't buy much though; n can't get uncomfortably big for n'th power / n'th root of integer types.
Last edited on Dec 6, 2013 at 5:17pm UTC