mercredi 2 octobre 2019

SFINAE-based ifdef

Trivia

It is safe to use #ifdef in case we want the compiler to optimize some part of the code away as shown in what follows.

#ifdef LOG
mtmd();
#endif

Hence, if LOG isn't defined during the compile time, there will be no overhead during execution.

Question

I'm interested to realize the same mechanism using SFINAE. A simplified version of the code is shown in what follows.

template <bool cond, typename std::enable_if<cond>::type* = nullptr>
inline void log(std::function<void()> func) {
  func();
}

template <bool cond, typename std::enable_if<!cond>::type* = nullptr>
inline void log(std::function<void()> func) {}

I can use it in the following form.

int main() {
  constexpr cond = true; // or flase
  log<cond>([&](){mtmd();});
}

The question is, when cond is false is there going to be any overhead or the compiler optimizes everything away since the log function is inline?

Aucun commentaire:

Enregistrer un commentaire