Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...