Reputation: 1232
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(void (*func)(int, int), int in, int out) {
(*func)(in, out);
}
template <bool cond, typename std::enable_if<!cond>::type* = nullptr>
inline void log(void (*func)(int, int), int in, int out) {}
I can use it in the following form.
void mtmd(int x, int y) { /* Do something */}
int main() {
constexpr cond = true; // or flase
int x, y;
log<cond>(&mtmd, x, y);
}
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
?
Upvotes: 0
Views: 184
Reputation: 10315
In general one can never be sure with inline
if it will work since it is more of a clue for the compiler than a real requirement (in the matter of the inlining of course, in matter of linkage and variables it is pretty strict). Of course it is highly probable that compiler will optimize away unnecessary calls to log
but it is not required by the standard. As said in cpp reference
Since this meaning of the keyword inline is non-binding, compilers are free to use inline substitution for any function that's not marked inline, and are free to generate function calls to any function marked inline.
To be sure you would have to use __forceinline
compiler extension
Upvotes: 1