Aussie AI
if constexpr statements
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
if constexpr
statements
There is an alternative usage of constexpr
in terms of “if
” statement conditions (since C++17):
if constexpr(cond)
This new syntax tags the condition as being amenable to computation at compile-time.
Hence, the compiler should optimize the if
statement to a constant value,
and it can then determine at compile-time which branch should be executed.
So, there is a double speedup from:
(a) the condition computation is removed at run-time, and
(b) code size reduction from unexecuted “dead code” being removed.
In fact, this determines at compile-time which code block will be parsed,
so there are cases where you can avoid a compile-time error in templates
by wrapping it inside an “if constexpr
” check.
This can be useful in compile-time situations such as template
expansion, where
you can prevent some expressions from being compiled, and also code bloat
can be reduced.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |