I found this function while reading and I can't find its definition on CPPreference
programming Principles by Bjarne stroustrup
It is used in this way:
ifs.read(as_bytes(x),sizeof(int));`
I understand how readworks but still can you help me with to_bytes standard definition.
The as_bytes function returns the address of the first byte of the argument (so the read call will overwrite the object x). Therefore in C++11 or later one would write that function as follows:
template <class T>
char* as_bytes(T& x) {
return &reinterpret_cast<char&>(x);
// or:
// return reinterpret_cast<char*>(std::addressof(x));
}
The version linked in the comments predates C++11. Presumably the reason why Stroustrup converts first to void* is because reinterpret_cast is not guaranteed to do the right thing in C++03. Note also that the old version will not work correctly for an argument that has an overloaded & operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With