简体   繁体   中英

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):

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM