如何使各种高度相似的类型的函数通用?

don*_*lan 0 c++ templates c++11

我有一个链接列表格式,不同类型的(int,double,例如):

struct DblNode {
    double value;
    DblNode * next;
}
struct IntNode {
    int value;
    IntNode * next;
}
Run Code Online (Sandbox Code Playgroud)

现在我正在为这些列表做些事情,我遇到的问题是我不断复制和粘贴函数,进行次要类型编辑:

DblNode * dbl_listind(DblNode * head,int ind){
    DblNode * position = head;
    int counter = 0;
    while(counter < ind){
        position = position -> next;
        counter++;
    }
    return position;
}
Run Code Online (Sandbox Code Playgroud)

然后重复int.

有没有办法以某种方式具有通用列表类型,然后以某种方式指定此功能,独立于我的链表的值成员的类型?

son*_*yao 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>;
Run Code Online (Sandbox Code Playgroud)

  • @bordeo [更好的头文件](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). (2认同)