How do I serialize and deserialize std::span in C++?

In C++, serialization and deserialization of data structures is a common requirement, especially when dealing with storage or network transmission. std::span represents a view over a contiguous sequence of elements, but it does not own its data, making serialization a bit different than other standard containers. Here, we will provide an example of how to serialize and deserialize a std::span in C++.

Example of Serializing and Deserializing std::span

#include <iostream>
#include <vector>
#include <span>

// Function to serialize std::span
template <typename T>
std::vector<T> serialize(std::span<T> span) {
    return std::vector<T>(span.begin(), span.end());
}

// Function to deserialize std::vector back to std::span
template <typename T>
std::span<T> deserialize(const std::vector<T>& vector) {
    return std::span<T>(const_cast<T*>(vector.data()), vector.size());
}

int main() {
    std::vector<int> values = {1, 2, 3, 4, 5};
    std::span<int> span(values.data(), values.size());

    // Serialize
    std::vector<int> serialized = serialize(span);

    // Deserialize
    std::span<int> deserialized = deserialize(serialized);

    // Output deserialized values
    for (int value : deserialized) {
        std::cout << value << ' ';
    }
    return 0;
}

C++ serialization deserialization std::span data structures