好的,我有这个模板类,它有点像单向列表。
template <typename T> List
它有这个内部函数 print
public:
void Print();
正如您所猜测的,它从头到尾打印列表内容;
然而,由于模板可以将类作为 T,可以想象,对于这种情况,我需要不同的 Print() 实现。例如,我有另一个类Point
class Point{
private:
int x, y;
public:
int getX();
int getY();
}
所以我想要专为积分设计的打印。我试过这个:
void List<Point>::Print();
但编译器告诉我
prototype for void List<Point> Print() doesn match any in class List<Point>
though
candidates are: from List<T> [with T = Point] void List<Point>::Print()
对我来说,这似乎是相同的功能。怎么了?如何编写 T 特定的模板类函数?
You use 显式模板专业化 http://en.cppreference.com/w/cpp/language/template_specialization使行为专门化Print
对于特定类型。
例如,对于Point
:
template <> // No template arguments here !
void List<Point>::Print() // explicitly name what type to specialize
{
//code for specific Point Print behaviour..
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)