看到一个求指数幂的 c++程序,有点不太懂为什么要用 static int const
#include <iostream>
template<int m, int n>
struct Power{
static int const value = m * Power<m,n-1>::value;
};
template<int m>
struct Power<m,0>{
static int const value = 1;
};
int main(){
std::cout << Power<2,10>::value << std::endl;//求解 2 的十次方
}
还有一个问题,请问 C++模板是在编译期就把递归改成迭代了吗?
附上我写的程序:
#include <iostream>
// Write your code here
template < int exponent>
int pow(int base )
{
return base*pow<exponent-1>(base);
}
template <>
int pow<0>(int base)
{
return 1;
}
int main() {
// Call function here
std::cout<< pow<10>(2)<<std::endl;
}