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

后端 未结 5 682
忘了有多久
忘了有多久 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:43

    Disclaimer: Noone can guarantee anything.

    That said, this an obvious and easy optimization for any compiler. It's quite safe to say that it will be optimized away, unless the optimizer is, well, practically useless.

    Since your "true" and "false" are constants, you are unambiguously creating an obvious dead branch in each class, and the compiler should optimize it away. Should is taken literally here - I would consider it a major, major problem if an "optimising" compiler did not do dead branch removal.

    In other words, if your compiler cannot optimize this, it is the use of that compiler that should be evaluated, not the code.

    So, I would say your gut feeling is correct: while yes, no "guarantees" as such can be made on each and every compiler, I would not use a compiler incapable of performing simplistic optimizations in any production environment, and of course not in any performance critical one. (In release builds of course).

    So, use it. Any modern optimizing compiler will optimize it away because it is a trivial optimization. If in doubt, check disassembly, and if it is not optimized, change the compiler to something more modern.

    In general, if you are writing any kind of performance-critical code, you must rely, at least to some extent, on compiler optimizations.

提交回复
热议问题