看到一个求指数幂的 c++程序,有点不太懂为什么要用 static int const

2020-07-31 21:06:55 +08:00
 weimo383

看到一个求指数幂的 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;
}
1181 次点击
所在节点    问与答
6 条回复
classyk
2020-07-31 21:08:49 +08:00
他那个编译期间就运算完成了。
weimo383
2020-07-31 21:33:32 +08:00
为什么要加 const ?
Tony042
2020-07-31 21:43:23 +08:00
@weimo383 加 const 和 static 都是为了优化,因为对于每个 specialization of power struct template 都是唯一且不变的,你写的代码是运行期计算的可以用 c++ 14 的 constexpr 来把你的代码改成编译期计算
PepperEgg
2020-08-01 09:22:13 +08:00
“加了 const,看了汇编,优化的连🐎都不认识” 忘了谁说的了 XD
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."
msg7086
2020-08-01 12:45:55 +08:00
const 可以改成 constexpr,编译期计算。
你写的那个版本也可以在 int pow 前面加上 constexpr 。

不过如果你用编译器优化的话,编译器会自己发现函数是 constexpr 的,然后自动优化成编译期计算。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/694732

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX