std::byte
Определён в заголовке <cstddef> | ||
|---|---|---|
enum class byte : unsigned char {};
| (начиная с C++17) |
std::byte — отдельный тип, реализующий понятие байта, определённое в спецификации языка C++.
Как и unsignedchar, он может использоваться для доступа к необработанной памяти, занимаемой другими объектами (представление объекта), но, в отличие от unsignedchar, не является ни символьным, ни арифметическим типом. std::byte представляет собой лишь набор битов и поддерживает только операции сдвига битов на целое число, а также побитовые операции и операции сравнения с другим значением типа std::byte.
Функции, не являющиеся членами
std::to_integer
template< class IntegerType > constexpr IntegerType to_integer( std::byte b ) noexcept; | (начиная с C++17) |
Эквивалентно: return IntegerType(b); Эта перегрузка участвует в разрешении перегрузки только в том случае, если std::is_integral_v<IntegerType> является true.
std::operator<<=,operator>>=
template< class IntegerType > constexpr std::byte& operator<<=( std::byte& b, IntegerType shift ) noexcept; | (1) | (начиная с C++17) |
template< class IntegerType > constexpr std::byte& operator>>=( std::byte& b, IntegerType shift ) noexcept; | (2) | (начиная с C++17) |
return b = b << shift; Эта перегрузка участвует в разрешении перегрузки только в том случае, если std::is_integral_v<IntegerType> является true.return b = b >> shift; Эта перегрузка участвует в разрешении перегрузки только в том случае, если std::is_integral_v<IntegerType> является true.
std::operator<<,operator>>
template< class IntegerType > constexpr std::byte operator<<( std::byte b, IntegerType shift ) noexcept; | (1) | (начиная с C++17) |
template< class IntegerType > constexpr std::byte operator>>( std::byte b, IntegerType shift ) noexcept; | (2) | (начиная с C++17) |
return std::byte(static_cast<unsigned int>(b) << shift); Эта перегрузка участвует в разрешении перегрузки только в том случае, если std::is_integral_v<IntegerType> является true.return std::byte(static_cast<unsigned int>(b) >> shift); Эта перегрузка участвует в разрешении перегрузки только в том случае, если std::is_integral_v<IntegerType> является true.
std::operator|=,operator&=,operator^=
constexpr std::byte& operator|=( std::byte& l, std::byte r ) noexcept; | (1) | (начиная с C++17) |
constexpr std::byte& operator&=( std::byte& l, std::byte r ) noexcept; | (2) | (начиная с C++17) |
constexpr std::byte& operator^=( std::byte& l, std::byte r ) noexcept; | (3) | (начиная с C++17) |
return l = l | r;.return l = l & r;.return l = l ^ r;. std::operator|,operator&,operator^,operator~
constexpr std::byte operator|( std::byte l, std::byte r ) noexcept; | (1) | (начиная с C++17) |
constexpr std::byte operator&( std::byte l, std::byte r ) noexcept; | (2) | (начиная с C++17) |
constexpr std::byte operator^( std::byte l, std::byte r ) noexcept; | (3) | (начиная с C++17) |
constexpr std::byte operator~( std::byte b ) noexcept; | (4) | (начиная с C++17) |
return std::byte(static_cast<unsigned int>(l) | static_cast<unsigned int>(r));.return std::byte(static_cast<unsigned int>(l) & static_cast<unsigned int>(r));.return std::byte(static_cast<unsigned int>(l) ^ static_cast<unsigned int>(r));.return std::byte(~static_cast<unsigned int>(b)); Примечания
Числовое значение n можно преобразовать в значение типа byte с помощью std::byte{n} благодаря правилам ослабленной инициализации enum class в C++17.
Байт можно преобразовать в числовое значение (например, чтобы получить целочисленный хеш объекта) обычным способом — с помощью явного преобразования или, альтернативно, с помощью std::to_integer.
| Макрос проверки наличия функции | Значение | Стандарт | Функция |
|---|---|---|---|
__cpp_lib_byte | 201603L | (C++17) |
std::byte |
Пример
#include <bitset>
#include <cassert>
#include <cstddef>
#include <iostream>
#include <utility>
std::ostream& operator<<(std::ostream& os, std::byte b)
{
return os << std::bitset<8>(std::to_integer<int>(b));
}
int main()
{
// std::byte y = 1; // Error: cannot convert int to byte.
std::byte y{1}; // OK
// if (y == 13) {} // Error: cannot be compared.
if (y == std::byte{13}) {} // OK, bytes are comparable
int arr[]{1, 2, 3};
// int c = a[y]; // Error: array subscript is not an integer
[[maybe_unused]] int i = arr[std::to_integer<int>(y)]; // OK
[[maybe_unused]] int j = arr[std::to_underlying(y)]; // OK
auto to_int = [](std::byte b) { return std::to_integer<int>(b); };
std::byte b{42};
assert(to_int(b) == 0b00101010);
std::cout << b << '\n';
// b *= 2; // Error: b is not of arithmetic type
b <<= 1;
assert(to_int(b) == 0b01010100);
b >>= 1;
assert(to_int(b) == 0b00101010);
assert(to_int(b << 1) == 0b01010100);
assert(to_int(b >> 1) == 0b00010101);
b |= std::byte{0b11110000};
assert(to_int(b) == 0b11111010);
b &= std::byte{0b11110000};
assert(to_int(b) == 0b11110000);
b ^= std::byte{0b11111111};
assert(to_int(b) == 0b00001111);
}
Вывод:
00101010
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/types/byte