Compile-time reversal of parameter-pack expansion

Viewed 729

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.

3 Answers

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)];
};

given that b is a non static data member, the following more compact version may turn out equivalent once optimized(*):

template<typename T>
struct Test {
public:
    template<typename... B>
    explicit Test(B... vv){ auto rb = std::rbegin(b); ((*rb++ = vv),...); }
private:
    char b[sizeof(T)];
};

(*) unless, Jarod42's solution ends up with the already reversed B's in data section when constexpr...

EDIT: it looks like both trunk clang and gcc are so smart to place the reversed B's in the data section both in Jarod42's code and mine !

You utilize index_sequence to extract items in reverse order:

#include <array>
#include <iostream>
#include <utility>
#include <cstddef>

template<::std::size_t... VIndexes> constexpr auto
Make_ReversedArrayOfBytes_Impl
(
    ::std::index_sequence<VIndexes...>
,   ::std::array<::std::byte, sizeof...(VIndexes)> bytes
)
{
    return
    (
        ::std::array<::std::byte, sizeof...(VIndexes)>
        {
            bytes[sizeof...(VIndexes) - 1 - VIndexes]...
        }
    );
}

template<typename... TItems> constexpr auto
Make_ReversedArrayOfBytes(TItems... bytes)
{
    return
    (
        Make_ReversedArrayOfBytes_Impl
        (
            ::std::make_index_sequence<sizeof...(TItems)>()
        ,   ::std::array<::std::byte, sizeof...(TItems)>
            {
                static_cast<::std::byte>(bytes)...
            }
        )
    );
}

int main()
{
    constexpr const auto items{Make_ReversedArrayOfBytes(0, 1, 2, 3, 4)};
    for(auto const & item: items)
    {
        ::std::cout << static_cast<::std::size_t>(item) << ::std::endl;
    }
    return 0;
}

Run in online compiler

Related