V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
weimo383
V2EX  ›  问与答

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

  •  
  •   weimo383 · 2020-07-31 21:06:55 +08:00 · 1159 次点击
    这是一个创建于 1335 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    不过如果你用编译器优化的话,编译器会自己发现函数是 constexpr 的,然后自动优化成编译期计算。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5432 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 63ms · UTC 08:34 · PVG 16:34 · LAX 01:34 · JFK 04:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.