Search code examples
c++variadic-templates

Compile-time reversal of parameter-pack expansion


In the following class template I want to initalize the member-array b with the values of the parameter-pack vv in reverse-oder!

template<typename T>
struct Test {
public:
    template<typename... B>
    explicit Test(B... vv) : b{vv...,} // how to initialize member b with pack expansion v... in reverse order
    {
    }
private:
    std::byte b[sizeof(T)];
};

I can't imagine how to reverse the parameter-pack expansion in a form, that it is as well usable in an initializer list.


Solution

  • With delegating constructor, you may do something like:

    template<typename T>
    struct Test {
        template <std::size_t...Is, typename... B>
        Test(std::index_sequence<Is...>, B&&... vv) :
            b{std::get<sizeof...(Is) - 1 - Is>(std::tie(vv...))...}
        {}
    
    public:
        template<typename... B>
        explicit Test(B... vv) : Test(std::index_sequence_for<B...>{}, vv...) {}
    private:
        std::byte b[sizeof(T)];
    };