Hello all, I am having some trouble creating and using a template based linked list and I hope you all can help me out. I have created a LinkedList class, and I am trying to use it in my main, but I get a unresolved external link error, that I hope you all can help me with.

LinkedList.h

#pragma once
#include <iostream>

using namespace std;

template < class T >
class LinkedList{ 

private:

class ListNode{ 

public:

T value; // Node value
ListNode *next; // Next Node
ListNode ( T v, ListNode *n = NULL) : value( v ), next( n ) { }
}; // ListNode

ListNode *head;

public:

LinkedList ( ListNode *ptr = NULL ) { head = ptr; }
~LinkedList ( void );
void appendNode ( T object);
void insertNode ( T object);
void deleteNode ( T object);
void displayList ( void );
}; // LinkedList


LinkedList.cpp

#include "LinkedList.h"

template < class T >
void LinkedList<T>::appendNode( T object ){ 
ListNode *newNode = new ListNode( object ), *nodePtr;
if ( !head )
head = newNode;
else { 
for ( nodePtr = head; nodePtr->next; nodePtr = nodePtr->next )
nodePtr->next = newNode;
}
}

I get the error in my main when I use the -> append, as so:

#include <iostream>
#include "LinkedList.h"

using namespace std;


int main(){

LinkedList<double> *myList = new LinkedList<double>;
myList->appendNode(45.67); //this is what gives me the error...


	return 0;
}

Can you help me out? Thanks!

Recommended Answers

All 2 Replies

I tried your code and it didn;t work, as you said. then I tried putting the implementation inside the class and is did work i.e.

// header file
template<class T>
class LinkedList{
//...
public:
void AddNode(){
   // addnode code here...
  }
};

Check out the following site, it states that class template implementations must be in the header file - I guess this means that an additional copy of the compiled member functions is produced for each file using the class... but I dunno.

http://www.bgsu.edu/departments/compsci/docs/templates.html

it says the following:

There is never an implementation file (*.cpp) for a template class. All of the member functions should be declared in the header file (in this case, table.h). The following shows how the functions for this class would be declared after the declaration of the class.

right; in fact, every instantiation of the templated may have a separate copy

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.