dimanche 22 janvier 2017

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?

Aucun commentaire:

Enregistrer un commentaire