QBugHunter
V2EX  ›  C++

关于模板元编程

  •  
  •   QBugHunter · Jan 25, 2021 · 2076 views
    This topic created in 1934 days ago, the information mentioned may be changed or developed.
    template<int x , int y>
    void printInfo();
    
    template<int x , int y>
    void printInfo(){
        std::cout<<(x + y);
    }
    
    //----
    printInfo<1,2>();
    

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

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

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

    顺便来点诡异的: https://godbolt.org/z/xrrcqv
    auto8888
        3
    auto8888  
       Jan 25, 2021
    @no1xsyzy 我去,大佬路子好野
    James369
        4
    James369  
       Jan 26, 2021
    你的代码怎么格式化的这么漂亮,怎么发贴含代码的?
    QBugHunter
        5
    QBugHunter  
    OP
       Jan 26, 2021
    @James369
    mark down 语法。。。。。
    James369
        6
    James369  
       Jan 26, 2021
    @QBugHunter 好的,谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5709 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 155ms · UTC 01:36 · PVG 09:36 · LAX 18:36 · JFK 21:36
    ♥ Do have faith in what you're doing.