Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use something like `std::basic_istream<std::byte>`

Tags:

c++

io

std

c++17

This question aims for using std::byte with standard input-output.

Are there any plans to add proper function overloads for read(_bytes) and write(_bytes) to the interfaces of basic_istream<CharT> and basic_ostream<CharT> in a future standard? What reasons speak against it? I understand that the CharT*-overloads should be kept. What can I do to use std::byte? I currently define in my project functions

std::istream& read(std::istream&, std::byte*, std::streamsize)
std::ostream& write(std::ostream&, const std::byte*, std::streamsize)

These use reinterpret_cast<> to char* resp. const char* but I believe this depends on the size of char. Am I wrong? Is char always 1 byte?

I tried to make std::basic_istream<std::byte> but it is missing std::char_traits<std::byte> and so on. Did anyone make this kind of thing work already?

like image 549
Maikel Avatar asked May 02 '17 10:05

Maikel


People also ask

What is byte* in C++?

std::byte is a distinct type that implements the concept of byte as specified in the C++ language definition. Like char and unsigned char, it can be used to access raw memory occupied by other objects (object representation), but unlike those types, it is not a character type and is not an arithmetic type.

Does C++ have a byte type?

@Ben: The C and C++ standards unambiguously define a "byte" as the size of a char , which is at least 8 bits.


2 Answers

P2146: Modern std::byte stream IO for C++ is a proposal related to your request. The status is tracked on Github.

like image 60
leezu Avatar answered Oct 07 '22 00:10

leezu


Don't.

Whether you're operating in "text mode" or "binary mode", what you are still doing fundamentally is acting on characters.

std::byte is not for this purpose, and that's why it does not have these features. Indeed, it was deliberately introduced not to have them!

enum class byte : unsigned char {} ; (since C++17)

std::byte is a distinct type that implements the concept of byte as specified in the C++ language definition.

Like char and unsigned char, it can be used to access raw memory occupied by other objects (object representation), but unlike those types, it is not a character type and is not an arithmetic type. A byte is only a collection of bits, and only bitwise logic operators are defined for it.

http://en.cppreference.com/w/cpp/types/byte


Did anyone make this kind of thing work already?

No, everyone deliberately didn't, as explored above.

Use char or unsigned char, as we have done for decades!

like image 33
Lightness Races in Orbit Avatar answered Oct 07 '22 02:10

Lightness Races in Orbit