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

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

    This is inherently up to the compiler, so you'd have to check the compiler's documentation or the generated code. But in simple cases like this, you can easily implement the optimization yourself:

    template 
    inline void doSomething();
    
    template<>
    inline void doSomething() {
        cout << "Hello" << endl;
    }
    
    template<>
    inline void doSomething() {
        cout << "Goodbye" << endl;
    }
    

    But "optimization" isn't really the right word to use since this might actually degrade performance. It's only an optimization if it actually benefits your code performance.

提交回复
热议问题