I would add a note that a template for and a switch can provide slightly different machine code output, even with all optimizations enabled. I discuss that a little bit here in a blogpost, where I change a switch statement to a template for in order to take advantage of reflection.
GCC ends up generating very similar code, but orders it a little bit differently. From some fiddling I came to the conclusion that it has to do with how GCC tries to assume the likely/unlikely paths differently, since GCC makes some assumptions about the likeliness of paths from how you order your switch cases, and it makes different assumptions for a sequence of if statements, which a template for will expand to. And that affects how GCC decides to arrange the machine code.
GCC's the only compiler with a mainline reflection implementation, and it's the compiler which is relevant for my project in that blogpost. So I didn't really check anything else. But it would seem the experimental Clang reflection branch also orders the machine code slightly different for a switch and a template for of if statements: https://compiler-explorer.com/z/xz4bx71or
Whether that's because it too has different assumptions for the likeliness of certain paths, I couldn't say.
View all comments
Show parent comment
10
u/friedkeenan May 12 '26
I would add a note that a
template forand aswitchcan provide slightly different machine code output, even with all optimizations enabled. I discuss that a little bit here in a blogpost, where I change aswitchstatement to atemplate forin order to take advantage of reflection.GCC ends up generating very similar code, but orders it a little bit differently. From some fiddling I came to the conclusion that it has to do with how GCC tries to assume the likely/unlikely paths differently, since GCC makes some assumptions about the likeliness of paths from how you order your
switchcases, and it makes different assumptions for a sequence ofifstatements, which atemplate forwill expand to. And that affects how GCC decides to arrange the machine code.