C++ variadic templates pack into std::array and unpack

  c++, templates

I want to pack variables in an array and then unpack using an interface like this

int x; float y; double z;
auto data = PackArray(x, y, z); // serializes without padding

...

int x; float y; double z;
UnpackArray(data, x, y, z); // copies data from the array to x, y, z

I tried

template<class... T>
constexpr size_t SumOfSizeofs(const T&...)
{
    return (sizeof(T) + ...);
}

// Creates array of u8 with size = sum(sizeofs)
template <class A, class ...Rest>
auto PackArray(A& a, Rest&... rest)
{
    return std::array<u8, SumOfSizeofs(a, rest...)>; // doesn't work
}

template <class Array, class...Rest>
auto UnpackArray(Array& array, Rest&... rest)
{
    // iterates through sizeof each element, copying to its new buffer from the array
}

If there was an std::packed_tuple it would be great… 🙁
I’m bad with template syntax, help?

Source: Windows Questions C++

LEAVE A COMMENT