J
James Kanze
It can be polished with some utility function templates:
// Name the cast properly, to self-document the code
template<typename T>
inline char* as_buffer(T& d)
{
return static_cast<char*>(static_cast<void*>(&d));
}
I think that there are cases where It still won't work (at least
in some cases, with g++)---even though the standard says it
should. (I think that there is an option in g++ which will make
it work. But since the overall approach is broken anyway,
there's no point.)
// Read binary data from input stream
template <typename T>
inline void read_n(T& d, std::istream& s, std::streamsize const& n)
{
if (!s)
throw std::runtime_error("input stream not readable");
s.read(as_buffer(d), n);
// good idea to check state of s
// one may need to handle endianness and swap bytes
}
Example, read 4 bytes from file stream ifs
int n = 0;
read_n(n, ifs, sizeof(n));
Of course, you won't necessarily read the same value that was
written, unless it was written by the same binary, running on
the same machine.
It should be also possible to specialize read_n function so
it's not necessary to give number of bytes explicitly.
Or just use sizeof in the function.
The only real problem is that the code only works in very
special cases.