std::as_bytes, std::as_writable_bytes
From cppreference.com
| ヘッダ <span> で定義 |
||
| template< class T, std::size_t N > std::span<const std::byte, S/* 以下参照 */> |
(1) | (C++20以降) |
| template< class T, std::size_t N > std::span<std::byte, S/* 以下参照 */> |
(2) | (C++20以降) |
span `s` の要素のオブジェクト表現へのビューを取得します。
もし `N` が std::dynamic_extent なら、返されるspan `S` のextentも std::dynamic_extent です。そうでない場合は、 sizeof(T) * N です。
as_writable_bytes は、 constexpr std::is_const_v<T> が false の場合にのみ、オーバーロード解決に参加します。
[編集] 戻り値
1) {reinterpret_cast<const std::byte*>(s.data()), s.size_bytes()} で構築されたspan。
2) {reinterpret_cast<std::byte*>(s.data()), s.size_bytes()} で構築されたspan。
[編集] 例
このコードを実行
#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); }
実行結果の例
3.14159 = { D8 0F 49 40 }
-3.14159 = { D8 0F 49 C0 }[編集] 関連項目
| オブジェクト表現を再利用して、与えられたストレージ内にオブジェクトを暗黙的に作成します (関数テンプレート) | |
| (C++17) |
バイト型 (enum) |