[英]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.