[英]How to make a function generic for various, highly similar types?
I have a linked list format that is of various types ( int
, double
, for instance): 我有各种类型的链表格式(例如
int
, double
):
struct DblNode {
double value;
DblNode * next;
}
struct IntNode {
int value;
IntNode * next;
}
And now I am doing things to these lists, and I run into the issue that I am constantly copying and pasting functions, making minor type edits: 现在,我正在处理这些列表,并且遇到了不断复制和粘贴函数,进行较小的类型编辑的问题:
DblNode * dbl_listind(DblNode * head,int ind){
DblNode * position = head;
int counter = 0;
while(counter < ind){
position = position -> next;
counter++;
}
return position;
}
And then duplicating for int
. 然后复制
int
。
Is there a way to somehow have a generalized list type, and then somehow specify this functionality, independent of the type of the value member of my linked list? 有没有办法以某种方式具有广义列表类型,然后以某种方式指定此功能,而与链接列表的值成员的类型无关?
That's what class/function templates supposed to do. 那就是类/函数模板应该做的。 eg
例如
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.