Namensräume
Varianten
Aktionen

std::as_bytes, std::as_writable_bytes

Von cppreference.com
< cpp‎ | container‎ | span
 
 
 
 
Definiert in Header <span>
template< class T, std::size_t N >

std::span<const std::byte, S/* siehe unten */>

    as_bytes( std::span<T, N> s ) noexcept;
(1) (seit C++20)
template< class T, std::size_t N >

std::span<std::byte, S/* siehe unten */>

    as_writable_bytes( std::span<T, N> s ) noexcept;
(2) (seit C++20)

Ermittelt eine Sicht auf die Objekt-Repräsentation der Elemente des Spans s.

Wenn N std::dynamic_extent ist, ist auch die Ausdehnung des zurückgegebenen Spans S std::dynamic_extent; andernfalls ist sie sizeof(T) * N.

as_writable_bytes nimmt nur an der Überladungsauflösung teil, wenn std::is_const_v<T> false ist.

[bearbeiten] Rückgabewert

1) Ein Span, konstruiert mit {reinterpret_cast<const std::byte*>(s.data()), s.size_bytes()}.
2) Ein Span, konstruiert mit {reinterpret_cast<std::byte*>(s.data()), s.size_bytes()}.

[bearbeiten] Beispiel

#include <cstddef>
#include <iomanip>
#include <iostream>
#include <span>
 
void print(float const x, std::span<const std::byte> const bytes)
{
    std::cout << std::setprecision(6) << std::setw(8) << x << " = { "
              << std::hex << std::uppercase << std::setfill('0');
    for (auto const b : bytes)
        std::cout << std::setw(2) << std::to_integer<int>(b) << ' ';
    std::cout << std::dec << "}\n";
}
 
int main()
{
    /* mutable */ float data[1]{3.141592f};
 
    auto const const_bytes = std::as_bytes(std::span{data});
 
    print(data[0], const_bytes);
 
    auto const writable_bytes = std::as_writable_bytes(std::span{data});
 
    // Change the sign bit that is the MSB (IEEE 754 Floating-Point Standard).
    writable_bytes[3] |= std::byte{0B1000'0000};
 
    print(data[0], const_bytes);
}

Mögliche Ausgabe

 3.14159 = { D8 0F 49 40 }
-3.14159 = { D8 0F 49 C0 }

[bearbeiten] Siehe auch

erstellt implizit Objekte in gegebenem Speicher, wobei die Objekt-Repräsentation wiederverwendet wird
(Funktions-Template) [edit]
(C++17)
der Byte-Typ
(enum) [bearbeiten]