I want to make a function which returns a power of integer. Please read the fmuecke's solution in power of an integer in c++ .
However, I want to generalize his solution to the arbitrary type T. Since c++11 has constexpr, I guess this is possible.
Naively, I tried something like,
template<class T, int N>
inline constexpr T pow(const T x){
return pow<N-1>(x) * x;
}
template<class T>
inline constexpr T pow<T, 1>(const T x){
return x;
}
template<class T>
inline constexpr T pow<T, 0>(const T x){
return 1;
}
Actually this approach failed since the partial specialization for function template is not allowed.
And one more question. I heard that it is up to the compiler whether the constexpr function is evaluated in compile time or not. How do I force it to compute for general type. I read from somewhere that one of the simplest hack for integral consts is to wrap it in std::integral_const::value.
See Question&Answers more detail:os