2017-01-22 17 views
0

我有一個鏈接列表格式,不同類型的(intdouble,例如):如何爲各種高度相似的類型製作通用函數?

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

有沒有辦法以某種方式有一個通用的列表類型,然後以某種方式指定此功能,獨立於我的鏈接列表的值成員的類型?

+4

你的意思是模板? – Rakete1111

+0

@ Rakete1111當然,我不知道(新的C++),但最好從頭開始,像這樣。非常簡單.. – bordeo

+3

你可能想檢查https://stackoverflow.com/documentation/c%2b%2b/460/templates – JVApen

回答

5

這就是類/功能模板應該做的。例如

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>; 
+0

太棒了,謝謝!快速提問:我是否在頭文件中定義了整個模板?或者跨頭文件和.cpp文件分割? – bordeo

+2

@bordeo [在頭文件中更好](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file)。 – songyuanyao

+0

好吧,明白了 - 謝謝! – bordeo

相關問題