Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a `span<std::byte>` from a single generic object?

I have a parameter of type const T& and want to turn it into std::span<const std::byte> or whatever the magic type that std::std::as_bytes spits out is. Ranges have a number of constructors, mostly aimed at containers, arrays etc. But I can’t seem to turn a single object into such a span. I feel like this is not an unreasonable thing to do.

edit: As an example, what doesn’t compile: const std::span<const std::byte> my_span(std::ranges::single_view{ object });

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Pointer to individual object can be treated the same way as pointer to an array of single object. You can create a span like this:

const T& t = value();
auto s = std::span<const T, 1>{std::addressof(t), 1};

You can then use std::as_bytes:

auto bytes = std::as_bytes(std::span<const T, 1>{std::addressof(t), 1});

Helper functions would probably be appropriate:

template<class T>
std::span<T, 1>
singular_span(T& t)
{
    return std::span<T, 1>{std::addressof(t), 1};
}

template<class T>
auto
singular_bytes(T& t)
{
    return std::as_bytes(singular_span(t));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading