2

I know I can use reinterpret_cast, but it seems weird that I can not go from char to "universal" type like std::byte. Is this just unfortunate mistake/limitation, or there is a reason for this?

Example:

int main(){
    std::string s{"abc"};
    std::byte* ptr  = static_cast<std::byte*>(s.data());
}
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • 2
    For the same reason you can't use `static_cast` to convert between `char *` and `unsigned char *` - `std::byte` is a distinct unrelated type. – Richard Critten Jan 26 '21 at 13:45
  • 3
    @SilvioMayolo `sizeof(char)` is per definition 1 byte, as `byte` is defined by `c++` as the size of `char`. `std::byte` is also an enum with the same size as `unsigned char`, so you are in fact guaranteed that `sizeof(char) == sizeof(std::byte)` by the standard. – Mestkon Jan 26 '21 at 13:46
  • @Mestkon Very good to know. Here I am assuming `std::byte` is defined to be 8 bits. Thanks for telling me! – Silvio Mayolo Jan 26 '21 at 13:48
  • 1
    It's not so much a mistake or limitation as the entire point and purpose of the type. `byte`'s whole purpose is to be memory without being a character or arithmetic type. – KitsuneYMG Jan 26 '21 at 13:50
  • Does this answer your question? [How to use new std::byte type in places where old-style unsigned char is needed?](https://stackoverflow.com/questions/46150738/how-to-use-new-stdbyte-type-in-places-where-old-style-unsigned-char-is-needed) – apple apple Jan 26 '21 at 14:12
  • @SilvioMayolo -- to be absolutely clear: just like `char` and its relatives, `std::byte` is required to be **at least** 8 bits. It can be larger. – Pete Becker Jan 26 '21 at 14:56

2 Answers2

6

Static cast only works between:

  1. Numerical types
  2. Possibly related class type pointers/referrnces (up and down).
  3. Pointers to/fom void pointers.
  4. Activating conversion constructors/operators

That is it.

Reinterpreting things as bytes is a reinterpret cast.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • Which one of those four items on your list would you say "converting an enum class to its underlying type" falls, or would that be a 5th item? – Chris Uzdavinis Mar 19 '21 at 21:45
2

In C++20 where std::span was added there are now as_bytes and as_writable_bytes that converts a span<T> to span<byte>. Internally it uses reinterpret_cast, but it makes the code a bit more readable/safe.

https://godbolt.org/z/zY9KPaz9K

#include <string>
#include <span>

void foo(){
    std::string s{"abc"};
    std::span<std::byte> t{std::as_writable_bytes(std::span<char>(s))};
}
Erik Man
  • 824
  • 4
  • 17