std::as_bytes, std::as_writable_bytes
来自 cppreference.cn
在头文件 <span> 中定义 |
||
template< class T, std::size_t N > std::span<const std::byte, S/* see below */> |
(1) | (C++20 起) |
template< class T, std::size_t N > std::span<std::byte, S/* see below */> |
(2) | (C++20 起) |
获取span s的元素的对象表示的视图。
如果N
是std::dynamic_extent,则返回的span S
的范围也是std::dynamic_extent;否则它是sizeof(T) * N。
as_writable_bytes
只有在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) |
字节类型 (枚举) |