如何为对象编写显式特化
Car<T>
在虚方法 clear() 中?
template <class U>
class List
{
public:
virtual void clear();
};
template <class T>
template <>
void List < Car <T> >::clear() //Specialization U = Car <T>, compiler error
{
....
}
类车:
template <class T>
class Car
{
T speed;
...
}
编译错误:
错误 16 error C3855: 'List': 模板参数 'Car' 与声明 h:...\List.hpp 不兼容 75 Error 20 error C2264: 'List::clear' : 函数定义或声明错误;函数未调用 h:...\List.hpp 75
但是这个构造是可以的
template <>
void List < Car <double> >::clear() //Specialization U = Car <T>, compiler error
{
....
}
最佳答案
我认为您可以这样做的唯一方法是:
template<class T>
class Car
{
};
template <class U>
class List
{
public:
virtual void clear();
};
template <class T>
class List<Car<T> >
{
public:
virtual void clear() { /* specialization */ }
};
或者,非内联版本:
template <class T>
class List<Car<T> >
{
public:
virtual void clear();
};
template <class T>
void List<Car<T> >::clear() {
/* specialization */
}
因为你不是真正的专业List<T>
但是,考虑到模板类型仍然出现,您只是对其进行了部分特化。无论如何,我的推论可能是错误的。
关于c++ - 显式特化,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4759251/