I've never serialized a structure to a file before in C++, so I'm looking for critique on my first try at it.
My main concerns are:
It uses the streams space-delimited behavior. If a
vector<char>
that contains a space is serialized, it skips the space, which results in an exception. From my tests, it works fine for non-whitespace elements, but I'd like any suggestions on how I could circumvent this problem.Should I be throwing an exception on bad reads? Am I throwing the right exception?
Should I be clearing the
vector
before adding to it while reading?The string formatting for the
runtime_error
s is ugly. I didn't want to introduce astringstream
just to format the message.
#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>
template <class T>
std::fstream& operator<<(std::fstream& fs, std::vector<T>& v) {
//Write size of vector
fs << v.size() << ' ';
//Write contents
for (T& t : v) {
fs << t << ' ';
}
return fs;
}
template <class T>
std::fstream& operator>>(std::fstream& fs, std::vector<T>& v) {
v.clear();
unsigned int vSize;
fs >> vSize;
if (!fs.good()) {
throw std::runtime_error(
std::string("Problem reading serialized vector size: ").append(std::to_string(vSize))
);
}
for (unsigned int i = 0; i < vSize; i++) {
T readT;
fs >> readT;
if (!fs.good()) {
unsigned long errPos = fs.tellg();
throw std::runtime_error(
std::string("Problem reading serialized vector content at ").append(std::to_string(errPos))
);
}
v.push_back(readT);
}
return fs;
}