看到一个求指数幂的 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; }
![]() | 1 classyk 2020-07-31 21:08:49 +08:00 他那个编译期间就运算完成了。 |
![]() | 2 weimo383 OP 为什么要加 const ? |
3 Tony042 2020-07-31 21:43:23 +08:00 @weimo383 加 const 和 static 都是为了优化,因为对于每个 specialization of power struct template 都是唯一且不变的,你写的代码是运行期计算的可以用 c++ 14 的 constexpr 来把你的代码改成编译期计算 |
![]() | 4 PepperEgg 2020-08-01 09:22:13 +08:00 “加了 const,看了汇编,优化的连都不认识” 忘了谁说的了 XD |
5 misdake 2020-08-01 10:04:42 +08:00 @PepperEgg https://www.bilibili.com/video/BV1bs411t7Y9?p=4&t=1670 "Is there some best practice about using 'const' anywhere possible?" "If you do not currently use 'const' anywhere you can, I bet you will after this talk." |
![]() | 6 msg7086 2020-08-01 12:45:55 +08:00 const 可以改成 constexpr,编译期计算。 你写的那个版本也可以在 int pow 前面加上 constexpr 。 不过如果你用编译器优化的话,编译器会自己发现函数是 constexpr 的,然后自动优化成编译期计算。 |