简体   繁体   中英

Using a partial template class as a specialized template function

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)
{
    //...
}

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& .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM