How to reverse the order of arguments of a variadic template function?

前端 未结 5 1154
猫巷女王i
猫巷女王i 2020-11-27 16:42

I have a template function with varargs template arguments, like this

template
void ascendingPrint(         


        
5条回答
  •  借酒劲吻你
    2020-11-27 17:38

    Here is a recursive implementation of a specialized revert<>:

    // forward decl
    template
    struct revert;
    
    // recursion anchor
    template<>
    struct revert<>
    {
        template
        static void apply(Un const&... un)
        {
            ascendingPrint(un...);
        }
    };
    
    // recursion
    template
    struct revert 
    {
        template
        static void apply(T const& t, Tn const&... tn, Un const&... un)
        {
            // bubble 1st parameter backwards
            revert::apply(tn..., t, un...);
        }
    };
    
    // using recursive function
    template
    void descendingPrint(A const& a, An const&... an)
    {
        revert::apply(an..., a);
    }
    

    It works with gcc-4.6/7/8 and clang and is probably standard compliant -- the only difficult part being the call of revert::apply(tn..., t, un...).

    It has drawbacks though (as recursion often has), that it generates a lot of template-instantiations of the target function (code bloat) and does not use perfect forwarding, which may be an issue (but maybe could be improved to use it).

提交回复
热议问题