std:: as_bytes, std:: as_writable_bytes
|
定义于头文件
<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
仅当
std::
is_const_v
<
T
>
为
false
时参与重载决议。
返回值
示例
#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}); // 更改符号位(即最高有效位,遵循 IEEE 754 浮点数标准)。 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)
|
字节类型
(枚举) |