I\'m implementing variadic min/max functions. A goal is to take advantage of the compile time known number of arguments and perform an unrolled evaluation (
There is a solution in C++17 which beats all answers proposed so far:
template
constexpr auto min(Head0 &&head0, Head1 &&head1, Tail &&... tail)
{
if constexpr (sizeof...(tail) == 0) {
return head0 < head1 ? head0 : head1;
}
else {
return min(min(head0, head1), tail...);
}
}
Notice how this:
Using gcc 10.2 with -O3, the accepted answer compiles to:
min(int, int, int):
cmp esi, edi
jge .L2
cmp esi, edx
mov eax, edx
cmovle eax, esi
ret
.L2:
cmp edi, edx
mov eax, edx
cmovle eax, edi
ret
There are more instructions and a conditional jump for whatever reason. My solution compiles only to:
min(int, int, int):
cmp esi, edx
mov eax, edi
cmovg esi, edx
cmp esi, edi
cmovle eax, esi
ret
This is identical to just calling std::min recursively for three parameters.
(see https://godbolt.org/z/snavK5)