Jump to content

  • Log In with Google      Sign In   
  • Create Account


Member Since 19 Jun 2004
Offline Last Active Nov 21 2012 01:46 AM

Topics I've Started

C++ templates

05 June 2006 - 03:47 AM

Prompted by another thread where someone was asking about double linked lists, as an exercise I made my own implementation based on inheritance from a List class. In order to avoid typecasts when accessing next and prev I templated it, a first for me. Now, I know there are some things I do which are horribly unsafe, but specifically with regard to the templating... is it stupid? The thing is, I can think of a number of situations where I might want to do something similar to avoid numerous typecasts when using inheritance (there are some typecasts in the List class, but at least not outside it).
#include <iostream>
using namespace std;

#define forAll(T,i,l) for(T* i = l->next; i != l; i = i->next)

template<class T> class List
  T* next;
  T* prev;
  List() { glue((T*)this); };
  ~List() {};
  void glue(T* n) { next = n; n->prev = (T*)this; };
  void remove() { prev->glue(next); };
  void del() { remove(); delete this; };
  void add(T* n) { prev->glue(n); n->glue((T*)this); };
  void merge(List* l) { prev->glue(l->next); l->prev->glue((T*)this); };
  bool isEmpty() { return next == this; };
  void purge() { while (!isEmpty()) next->del(); } 
  int size() { int count = 0; forAll(T,i,this) ++count; return count; };

class MyClass : public List<MyClass>
  int myData;
  MyClass(int data) { myData = data; };

int main(int argc, char** argv)
  // Create 2 lists
  List<MyClass>* list1 = new List<MyClass>();
  List<MyClass>* list2 = new List<MyClass>();
  // Add a node to each
  list1->add(new MyClass(1));
  list2->add(new MyClass(2));
  // Merge lists
  delete list2;
  // Traverse list and output data
  forAll(MyClass,i,list1) cout << i->myData << endl;
  // Delete nodes
  // Delete the list
  delete list1;
  // Done

Another STL question

22 April 2006 - 08:12 AM

I have a dataholder class, instances of which I need to place in a list. A simplified version:
class Dataholder
    int data;
    void remove();
Here the remove function must remove the dataholder from the list. However, since I couldn't figure out how to do this if I placed dataholders in an STL vector, I found myself forced to implement my own version of vectors. Is there a way to do what I need to do with STL? Thanks in advance.