1
votes

I have a template, and I want to specialize it using a vector (which is a template itself). It is possible?

Here is the compiler error: error C2768: 'serialize' : illegal use of explicit template arguments.

A little example of what I need to do:

template<typename T>
void serialize(T data, Stream& stream)
{
    //...
}

template<typename MT>
void serialize<map<string, MT>>(map<string, MT> data, Stream& stream)
{
    //...
}
1
Okay, so I can't specialize my template function with a partial templated class? - Antoine
I take that back. You can't do partial specialization of function templates. - R Sahu

1 Answers

1
votes

There is no partial specialization of function templates.

There is only full specialization (which is usually a bad idea), and overloading.

template<typename MT>
void serialize(map<string, MT> data, Stream& stream)
{
  //...
}

would be an overload. If you always allowed type deduction to happen, it would probably behave like you would expect specialization to work.

Stick any std namespace stuff you want to support in the namespace of serialize. Stick other serialize overloads in the namespace of the class you want to change the behavior of.


If you really, really need partial specialization, forward your work into a template class, and do partial specialization of that class.

template<class T>
struct serialize_impl {
  void operator()(T data, Stream& stream) const {
    // ...
  }
};
template<class MT>
struct serialize_impl<map<string, MT>> {
  void operator()(map<string MT> data, Stream& stream) const {
    // ...
  }
};

then

template<class T>
void serialize(T data, Stream& stream) {
  serialize_impl<T>{}(data, stream);
}

however this is often a bad idea, and overloading is usually the right thing to do.

Also, don't take things by value when serializing. Take then by T const&.