问题描述
我正在将一个简单的数据写入 XML 序列化程序以进行培训.这个想法是将值传递给序列化函数,该函数将执行某些操作将给定值转换为字符串格式.许多类型确实具有内置转换,但对于许多类型,我希望有一个专门的函数来执行此操作.我的方法是:
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();
}
但是当我编译它 (g++ 4.6.2) 时,我得到 error: function template partial specialization ‘serialize<std::vector<T*>>' 是不允许的
.有没有办法做到这一点?
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.
template<class T> void serialize(T *value, Serializer *serializer);
仍然可以提供默认实现,但是如果像
can still provide a default implementation, but if a more specialized version like
void serialize(bool *value, Serializer *serializer);
存在,它将被重载决议首选.这允许您简单地定义一个函数,如
exists, it will be preferred by the overload resolution.This allows you to simply define a function like
template <typename T> void serialize(::std::vector<T> *value, Serializer *serializer);
将调用向量.(考虑到 ::std::vector 比 T 更专业,因此重载决议将在可能的情况下选择此函数).
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).
这篇关于使用泛型类专门化模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!