std::as_byt...table_bytes(3)
π NAME π
Okay bestie, this page comes straight out of the C++ Standard Libary manual β yes, that spelling, weβre keeping it π
β and itβs all about std::as_bytes,std::as_writable_bytes. The page literally says std::as_bytes,std::as_writable_bytes again, and honestly? Iconic.
πΈ Synopsis πΈ
Defined in header <span>:
template< class T, std::size_t N >
std::span<const std::byte, S/* see below */> (1) (since C++20)
as_bytes( std::span<T, N> s ) noexcept;
template< class T, std::size_t N >
std::span<std::byte, S/* see below */> (2) (since C++20)
as_writable_bytes( std::span<T, N> s ) noexcept;
So the vibe is: you get a view to the object representation of the elements of the span s β¨.
If N is std::dynamic_extent, the extent of the returned span S is also std::dynamic_extent; otherwise it is sizeof(T) * N. No cap.
Also important, bestie: as_writable_bytes only participates in overload resolution if std::is_const_v<T> is false. Periodt π«Ά.
β¨ Return value β¨
- A span constructed with
{reinterpret_cast<const std::byte*>(s.data()), s.size_bytes()}. Cute, const-safe, slay. - A span constructed with
{reinterpret_cast<std::byte*>(s.data()), s.size_bytes()}. Writable version, letβs go π₯.
π Example π
// Run this code
#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);
}
Possible output:
3.14159 = { D8 0F 49 40 }
-3.14159 = { D8 0F 49 C0 }
π¦ See also π¦
start_lifetime_as(C++23) β implicitly creates objects in given storage with the object representation reused (function template)start_lifetime_as_array(C++23) β implicitly creates objects in given storage with the object representation reused (function template)byte(C++17) β the byte type (enum)
Thatβs the whole page, bestie π«Ά. Source/version vibes: http://cppreference.com, dated 2024.06.10 β go off, C++20/C++23 era π
β¨.
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms