名稱空間
變體
操作

std::as_bytes, std::as_writable_bytes

來自 cppreference.com
< cpp‎ | 容器‎ | span
在標頭檔案 <span> 中定義
template< class T, std::size_t N >

std::span<const std::byte, S/* see below */>

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

std::span<std::byte, S/* see below */>

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

獲取span s的元素的物件表示的檢視。

如果Nstd::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)
位元組型別
(列舉) [編輯]
English 日本語 中文(简体) 中文(繁體)