[英]How to make a function generic for various, highly similar types?
我有各种类型的链表格式(例如int
, double
):
struct DblNode {
double value;
DblNode * next;
}
struct IntNode {
int value;
IntNode * next;
}
现在,我正在处理这些列表,并且遇到了不断复制和粘贴函数,进行较小的类型编辑的问题:
DblNode * dbl_listind(DblNode * head,int ind){
DblNode * position = head;
int counter = 0;
while(counter < ind){
position = position -> next;
counter++;
}
return position;
}
然后复制int
。
有没有办法以某种方式具有广义列表类型,然后以某种方式指定此功能,而与链接列表的值成员的类型无关?
那就是类/函数模板应该做的。 例如
template <typename T>
struct Node {
T value;
Node * next;
}
template <typename T>
Node<T> * listind(Node<T> * head,int ind){
Node<T> * position = head;
int counter = 0;
while(counter < ind){
position = position -> next;
counter++;
}
return position;
}
// optional
using DblNode = Node<double>;
using IntNode = Node<int>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.