Implementing variadic min / max functions

后端 未结 6 1945
灰色年华
灰色年华 2020-12-14 06:06

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 (

6条回答
  •  不知归路
    2020-12-14 07:08

    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:

    • requires only one function
    • you can't call this with fewer than two parameters
    • it compiles optimally

    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)

提交回复
热议问题