Nov 23, 2014

[C++][algorithm] compile time pow


template<class T>
inline constexpr T pow(const T base, unsigned const exponent)
{
    // (parentheses not required in next line)
    return (exponent == 0)     ? 1 :
           (exponent % 2 == 0) ? pow(base, exponent/2)*pow(base, exponent/2) :
           base * pow(base, (exponent-1)/2) * pow(base, (exponent-1)/2);
}

Reference:
c++ power of integer, template meta programming

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.