V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
QBugHunter
V2EX  ›  C++

关于模板元编程

  •  
  •   QBugHunter · 2021-01-25 11:11:11 +08:00 · 1449 次点击
    这是一个创建于 1158 天前的主题,其中的信息可能已经有所发展或是发生改变。
    template<int x , int y>
    void printInfo();
    
    template<int x , int y>
    void printInfo(){
        std::cout<<(x + y);
    }
    
    //----
    printInfo<1,2>();
    

    对于这样一个函数调用,x+y 是在编译器计算的,还是在运行期间计算的?

    6 条回复    2021-01-26 15:41:44 +08:00
    fengjianxinghun
        1
    fengjianxinghun  
       2021-01-25 11:18:07 +08:00
    1. 这算不上元编程。
    2. x+y 开优化的情况是编译期,常量传播。
    no1xsyzy
        2
    no1xsyzy  
       2021-01-25 12:21:21 +08:00
    gcc 10.2 -O0 也是编译期完成计算 https://godbolt.org/z/3dbYhW
    开优化会 inline (但不确定是否必然 inline )

    但考虑到 + 可以被重载,这应当被视为 int 特性而不是模板特性。

    顺便来点诡异的: https://godbolt.org/z/xrrcqv
    auto8888
        3
    auto8888  
       2021-01-25 13:39:34 +08:00
    @no1xsyzy 我去,大佬路子好野
    James369
        4
    James369  
       2021-01-26 10:02:36 +08:00
    你的代码怎么格式化的这么漂亮,怎么发贴含代码的?
    QBugHunter
        5
    QBugHunter  
    OP
       2021-01-26 15:22:42 +08:00
    @James369
    mark down 语法。。。。。
    James369
        6
    James369  
       2021-01-26 15:41:44 +08:00
    @QBugHunter 好的,谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3747 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:14 · PVG 08:14 · LAX 17:14 · JFK 20:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.