I am writing a simple data to XML serializer for training purposes. The idea is to pass values to a serialize function that will do something to bring the given values into a string format. Many types do have built in conversions, but for many I want to have a specialized function doing this. My approach is:
I have a template function with this signature:
template <class T> void serialize(T *value, Serializer *serializer);
and I can specialize the template like this:
template <> void serialize<bool>(bool *value, Serializer *serializer);
Works fine. Now I want to write a serialize function for a vector, as in:
template <class T> void serialize<std::vector<T*> >(std::vector<T*> *value, Serializer *serializer) {
serializer->begin_section("array");
for(std::vector<T*>::iterator it = value->begin(); it != value->end(); it++) {
serializer->add_value(*it);
}
serializer->end_section();
}
But when I compile it (g++ 4.6.2), I get error: function template partial specialization ‘serialize<std::vector<T*> >’ is not allowed. Is there a way I can do this?
Your problem is that you wish to provide a template specialization that is a template itself.
The simplest way to resolve your problem is to not use template specialization at all and instead rely on function overloading.
can still provide a default implementation, but if a more specialized version like
exists, it will be preferred by the overload resolution.
This allows you to simply define a function like
that will be called for vectors. (Consider that ::std::vector is more specialized than T, so overload resolution will pick this function where it is possible).