Is there anything particularly bad or naive about reading serialized data (of a known format + endianness) from a file using something like this? I’m not worried about portability and realistically it would only be used by me. I know one issue would be attempting to extract to a non-packed POD struct, although I can always define a separate operator> for each such struct.
template<typename T> inline std::fstream& operator> (std::fstream& fs, T& i) {
static_assert(std::is_pod<T>::value, "Not POD");
fs.read(reinterpret_cast<char*>(&i), sizeof i);
return fs;
}
template<typename T> inline std::fstream& operator> (std::fstream& fs, std::vector<T>& v) {
static_assert(std::is_pod<T>::value, "Not POD");
fs.read(reinterpret_cast<char*>(&v[0]), sizeof(T) * v.size());
return fs;
}
template<typename T> inline std::fstream& operator> (std::fstream& fs, std::vector<std::vector<T>>& v) {
for (auto& i : v)
fs > i;
return fs;
}
inline std::fstream& operator> (std::fstream& fs, std::string& s) {
fs.read(reinterpret_cast<char*>(&s[0]), s.size());
return fs;
}
std::fstream f("file", std::ifstream::in | std::ifstream::out | std::ifstream::binary);
int i;
char j;
std::vector<std::vector<char>> vec(5, std::vector<char>(8));
f > i > j > vec;
I’m not sure what you’re asking. The code you post doesn’t read
serialized data “of a known format or endianness”. It copies bytes from
the file to where ever, which could result in undefined behavior, and is
very unlikely to result in the correct values unless by some weird bit
of luck, the “known format” corresponds exactly to that used internally
on your machine. I a lot of cases, in fact, it will probably cause the
program to crash; think of what might happen if the structure you’re
trying to read contains a pointer, for example.
I might add that overloading ‘>’ for this is horrible overload abuse; if
you want to read a special format, the logical way to go about it is to
define a corresponding class (
ixdrstream, for example), and overload‘>>’ for it. (
ixdrstreamwill probably derive fromstd::basic_ios<char>, of course, and will almost certainly use thestandard
streambuffor actual input.)And of course, you never overload on
std::fstream, but rather onstd::istream(orstd::ostreamfor output). (FWIW, I don’t thinkI’ve ever used an
std::fstream. The stream idiom really doesn’tsupport mixing reads and writes elegantly.)