C++ use templates to avoid compiler from checking a boolean

后端 未结 5 673
忘了有多久
忘了有多久 2021-02-12 13:51

Let\'s say I have a function:

template 
inline void doSomething() {
    if(stuff) {
        cout << \"Hello\" << endl;
    }
    el         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-12 14:24

    Compilers are really good at constant folding. That is, in this case it would surprise me if the check would stay until after optimization. A non-optimized build might still have the check. The easiest way to verify is to create assembler output and check.

    That said, it is worth noting that the compiler has to check both branches for correctness, even if it only ever uses one branch. This frequently shows up, e.g., when using slightly different algorithms for Random Access Iterators and other iterators. The condition would depend on a type-trait and one of the branches may fail to compile depending on operations tested for by the traits. The committee has discussed turning off this checking under the term static if although there is no consensus, yet, on how the features would look exactly (if it gets added).

提交回复
热议问题