0

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?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Chris
  • 28,822
  • 27
  • 83
  • 158
  • 4
    You mean templates? – Rakete1111 Jan 22 '17 at 16:36
  • @Rakete1111 sure, I don't know about that (new to c++) but preferably something from scratch, like this. Very simple.. – Chris Jan 22 '17 at 16:37
  • 3
    You might want to check https://stackoverflow.com/documentation/c%2b%2b/460/templates – JVApen Jan 22 '17 at 16:38
  • 1
    Do yourself a favour and use `std::list` or `std::forward_list` if you *really* need the semantics of a linked list. – Christian Hackl Jan 22 '17 at 17:00
  • @ChristianHackl for sure. that will be next weekend :) Right now, I'm just going for a faster implementation of code I wrote in python, and also a c++ learning opportunity. – Chris Jan 22 '17 at 17:08

1 Answers1

5

That's what class/function templates supposed to do. e.g.

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>;
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Awesome, thank you! Quick question: Do I define the entire template in the header file? Or split across header and .cpp file? – Chris Jan 22 '17 at 16:45
  • 2
    @bordeo [Better in header file](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). – songyuanyao Jan 22 '17 at 16:46