Template function specialization with a generic class

I am writing simple data for an XML serializer for educational purposes. The idea is to pass the values ​​to a serialization function, which will do something to convert the given values ​​to a string format. Many types have built-in conversions, but for many I want you to have a specialized function. My approach:

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 great. Now I want to write a serialization 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?

+3


source to share


2 answers


Your problem is that you want to provide a template specialization, which is the template itself.

The easiest way to solve your problem is to not use template specialization at all and rely on function overloading instead.

template<class T> void serialize(T *value, Serializer *serializer);

      

may still provide a default implementation, but if a more specialized version like



void serialize(bool *value, Serializer *serializer);

      

exists, it would be preferred overload resolution. This allows you to simply define a function like

template <typename T> void serialize(::std::vector<T> *value, Serializer *serializer);

      

which will be called for vectors. (Note that :: std :: vector is more specialized than T, so overload resolution will choose this function where possible).

+2


source


You can overload serialize()

, for example :

#include <iostream>
#include <vector>

template <class T> void serialize(T *, char *)
{
    std::cout << "T\n";
}

template <class T> void serialize(std::vector<T*> *, char *)
{
    std::cout << "vector\n";
}

int main()
{
    int a = 1;
    std::vector<int*> x;

    serialize(&a, 0);
    serialize(&x, 0);

    return 0;
}

      



Output:

T
vector

      

+1


source







All Articles