简体   繁体   中英

Template specialization vs. Compiler optimization

I have a class with a boolean template argument.

template<bool b>
class Foo {
  void doFoo();
};

I want doFoo to do different things based on the value of b .

Naively I could write

Option 1

template<bool b> void Foo<b>::doFoo() {
  if (b) cout << "hello";
  else cout << "goodbye";
}

This seems inefficient to me because I have to execute an if every time the function is called event though the correct branch should be known at compile time. I could fix this with template specialization:

Option 2

template<> void Foo<true>::doFoo() { cout << "hello"; }
template<> void Foo<false>::doFoo() { cout << "goodbye"; }

This way I don't have any conditionals executed in runtime. This solution is a bit more complicated (especially since in my real code the class has several template arguments and you can't partially specialize functions so I will need to wrap the function in a class).

My question is, is the compiler smart enough to know not to execute the conditional in option 1 since it always executes the same way or do I need to write the specializations? If the compiler is smart enough I would be happy to know if this is compiler dependent or a language feature that I can rely on?

The compiler will probably optimize the branch away since it is known at compile time what b is. This is not guaranteed though and the only way to know for sure is to check the assembly.

If you can use C++17 you can use if constexpr and that guarantees only one branch will exist.

This seems inefficient to me because I have to execute an if every time the function is called

The compiler will probably optimize this away - but it's not guaranteed by the standard. To be certain, you should look at the output of the compiler you care about (with the compile options you plan to use): eg. clang doesn't have a branch in the linked example (the un-optimized version has lots of function call boilerplate but no branch).

In C++17 you can use if constexpr , and the branch not taken will be discarded at compile time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM