你的代码没有编译,如果可能的话,你应该先检查你的代码编译,使用你的编译器,或者先在编译器资源管理器上检查它。
此外,您忘记考虑负值。这是整体权力的一个非常重要的特征。下面的代码适用于常规 int 类型。我将让您探索如何将它扩展到其他整数类型。
#include <type_traits>
#include <iostream>
#include <cmath>
#include <limits>
using namespace std;
template <typename T>
enable_if_t< is_integral<T>::value, T>
mypow(T base, unsigned int exp)
{
T result = T(1);
bool sign = (base < 0);
if (sign) base = -base;
T temp = result;
while(exp-- != 0)
{
temp *= base;
if (temp < result)
{
return (sign) ? numeric_limits<T>::min()
: numeric_limits<T>::max();
}
result = temp;
}
return (sign && (exp & 1)) ? -result : result;
}
template <typename T>
enable_if_t< !is_integral<T>::value, int>
mypow(const T& base, unsigned int exp)
{
T result = T(1);
int i_base = int(floor(base + .5));
bool sign = (i_base < 0);
if (sign) i_base = -i_base;
int temp = result;
while(exp-- != 0)
{
temp *= i_base;
if (temp < result)
{
return (sign) ? numeric_limits<int>::min() : numeric_limits<int>::max();
}
result = temp;
}
return (sign && (exp & 1)) ? -result : result;
}
在现实生活中,我会注意地板的使用,即使是在积分情况下。
template<typename T>
enable_if_t< is_integral<T>::value, T>
mypow(T x, unsigned int y) { return T(floor(pow(x, y) + .5)); }
template<typename T>
enable_if_t< !is_integral<T>::value, int>
mypow(T x, unsigned int y) { return int(floor(pow(floor(x + .5), y) + .5)); }