模板类特定类型的功能 [英] Template class type-specific functions

查看:111
本文介绍了模板类特定类型的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我有这个模板类,有点像单向列表.

Ok, so i have this template class, which is kinda like one-way list.

template <typename T> List

并且具有内部打印功能

public:
void Print();

您可能会猜到的

从头到尾打印列表内容; 但是,由于模板可以将类视为T,因此可以想象,在这种情况下,我将需要Print()的不同实现.例如,我还有另一个班级Point

which, as you can guess, prints the list contents from begining to end; However, as template can take classes as T, one can imagine, that i would need different implementations of Print() for that very cases. For example, I have another class Point

class Point{
 private:
  int x, y;
 public:
  int getX();
  int getY();
}

所以我想要专门为积分设计的打印.我试过了:

so i want Print specifically designed for Points. I tried this:

void List<Point>::Print();

但是编译器告诉我

prototype for void List<Point> Print() doesn match any in class List<Point>

尽管

candidates are: from List<T> [with T = Point] void List<Point>::Print()

对我来说,这似乎是一样的功能.怎么了?以及如何编写特定于T的模板类函数?

For me it seems like the same fucntion. What's wrong? And how do I write T-specific template class functions?

推荐答案

您使用显式模板专门化,以专门针对特定类型的Print行为.

You use explicit template specialization to specialize behaviour of Print for specific types.

例如,对于Point:

template <> // No template arguments here !
void List<Point>::Print() // explicitly name what type to specialize
{
  //code for specific Point Print behaviour..
}

这篇关于模板类特定类型的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆