2017-01-22 36 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

相关问题