简体   繁体   中英

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

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?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM