std::basic_...stream::span(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::basic_...stream::span(3) πŸ’–

okay bestie, welcome to the C++ Standard Libary page for std::basic_...stream::span(3) β€” manual-name folded in right here, exactly as the header spells it. We're talking about std::basic_spanstream::span, and yes it's giving niche-but-useful C++23 energy. πŸ¦‹


✨ NAME ✨

std::basic_spanstream::span β€” literally std::basic_spanstream::span. That's the name, no plot twist. πŸ’…

🌟 Synopsis 🌟

std::span<CharT> span() const noexcept;   (1) (since C++23)
void span( std::span<CharT> s ) noexcept; (2) (since C++23)
  1. Gets a span referencing the written area if std::ios_base::out is set in the open mode of the wrapped std::basic_spanbuf, or a span referencing the underlying buffer otherwise.
  2. Makes the wrapped std::basic_spanbuf perform I/O on the buffer referenced by s.

🌸 Parameters 🌸

  • s β€” a std::span referencing the storage that's gonna be used as the new underlying buffer of the stream. 🫢

πŸ’« Return value πŸ’«

  1. A std::span referencing the underlying buffer or written area, depending on the open mode of the wrapped std::basic_spanbuf.
  2. (none) β€” yep, nothing comes back. πŸ’€

πŸ”₯ Example πŸ”₯

The page says // Run this code, so go off, bestie:

#include <cassert>
#include <iostream>
#include <span>
#include <spanstream>

int main()
{
    char out_buf[16];
    std::ospanstream ost{std::span<char>{out_buf}};
    ost << "C++" << ' ' << 23 << '\0'; // note explicit null-termination
    auto sp = ost.span();
    assert(
        sp[0] == 'C' && sp[1] == '+' && sp[2] == '+' &&
        sp[3] == ' ' && sp[4] == '2' && sp[5] == '3' &&
        sp[6] == '\0'
    );
    std::cout << "sp.data(): [" << sp.data() << "]\n";
    std::cout << "out_buf: [" << out_buf << "]\n";
    // spanstream uses out_buf as internal storage, no allocations
    assert(static_cast<char*>(out_buf) == sp.data());

    const char in_buf[] = "X Y 42";
    std::ispanstream ist{std::span<const char>{in_buf}};
    assert(static_cast<const char*>(in_buf) == ist.span().data());
    char c;
    ist >> c;
    assert(c == 'X');
    ist >> c;
    assert(c == 'Y');
    int i;
    ist >> i;
    assert(i == 42);
    ist >> i; // buffer is exhausted
    assert(!ist);
}

🌈 Output 🌈

sp.data(): [C++ 23]
out_buf: [C++ 23]

πŸ‘‘ See also πŸ‘‘

  • span β€” obtains or initializes an underlying buffer according to mode (C++23) (public member function of std::basic_spanbuf<CharT,Traits>).

source: http://cppreference.com Β· version/date: 2024.06.10 Β· std::basic_...stream::span(3) β€” mwah, hydrate and go read your spans, bestie πŸ’–βœ¨

πŸ“¦ where this page comes from