Nested/recursive template specialization
I'm trying to write some naive binary serialization code and wanted to cut down on repetition of logic for serializing/deserializing nested vectors or other STL containers to reduce the chance of typos etc, and thought templates might hold a solution for me.
Apologies if some of my naming/conventions look like bastardized C#/Java, it's been a while since I've used C++.
Code:
template <typename T> void serializeField(IWriter& writer, const T& val) {
writer.write((char*)&val, sizeof(T));
}
template<typename U, typename V>
template <> void serializeField(IWriter& writer, const U<V>& collection)
{
serializeField(writer, (unsigned long)col.size());
for (typename U<typename V>::const_iterator
i = collection.begin();
i != collection.end();
++i)
{
serializeField(writer, *i);
}
}
With the goal of being able to do something like:
Code:
// main, or wherever
StlWriter myWriter(my_ofstream);
int val;
serializeField(myWriter, val);
vector<int> valVector;
serializeField(myWriter, valVector);
list<int> valList;
serializeField(myWriter, valList);
vector<vector<int> > nestedVector;
serializeField(myWriter, nestedVector);
Is there a way to do something like this? It isn't a big deal for me to just manually write code to serialize my vectors to the needed depth, but it sure would be nice to get this working.