1

Why I still got link error LNK2019 even though I defined and implemented template in the same file? Here is my code:

#ifndef _LINKEDLIST_H_
#define _LINKEDLIST_H_

#include <iostream>
using namespace std;

template <class T>
class LinkedList
{
private:
    struct node
    {
        T data;
        node* pNext;
    };
    node* pHead;
    node* pTail;
    int count;
public:
    LinkedList();
    ~LinkedList();
    bool isEmpty();
    int getLength();
    bool insert(int position, T value);
    bool remove(int position);
    bool addHead(T value);
    bool addTail(T value);
    bool removeHead();
    bool removeTail();
    void clear();
    T getEntry(int position);
    void setEntry(int position, T value);
};

template <class T>
LinkedList<T>::LinkedList();

template <class T>
LinkedList<T>::~LinkedList();

template <class T>
bool LinkedList<T>::isEmpty();

template <class T>
int LinkedList<T>::getLength();

template <class T>
bool LinkedList<T>::insert(int position, T value);

template <class T>
bool LinkedList<T>::remove(int position);

template <class T>
bool LinkedList<T>::addHead(T value);

template <class T>
bool LinkedList<T>::addTail(T value);

template <class T>
bool LinkedList<T>::removeHead();

template <class T>
bool LinkedList<T>::removeTail();

template <class T>
void LinkedList<T>::clear();

template <class T>
T LinkedList<T>::getEntry(int position);

template <class T>
void LinkedList<T>::setEntry(int position, T value);

#endif

And how to split it into two file? I searched and find some methods like include both .h and .cpp in main file or include .cpp in .h file but it didn't work.

H.L.Alumnus
  • 69
  • 1
  • 6

1 Answers1

0

The answer to the above question, as written in some comments, is that you were not defining but just declaring the template:

template <class T>
class LinkedList
{
 ...
public:
    LinkedList();
    ~LinkedList();
    ...
};

template <class T>
LinkedList<T>::LinkedList(); // Not a definition

and regarding your question "can I split it into cpp and h files?" there's another different question which addresses the issue in depth: Why can templates only be implemented in the header file?

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246