Search code examples
c++templates

Why is Linked list not considered a template?


I am trying to make a template LinkedList class, but when I try to compile, I get this error "LinkedList.cpp:11:7: error: 'LinkedList' is not a template". I think it might have something to do with Node.cpp adding LinkedList as a friend class, but I am new to c++, so I don't know, and if it is something to do with the friend class, I do not know how to fix it.

I wanted to make a linkedList class, but I ran into an error with templates. I ran into this problem on an earlier project, and it bested me, so I gave up. I tried messing with the multiple inclusion defense, changing where my code was(template header file code in the normal file, ect.) , and I tried using chat gpt to no avail.

I don't know for sure what the issue is, so I have given all 4 of my files they are LinkedList.cpp, LinkedList.h, Node.cpp, and test.cpp. LinkedList.cpp, LinkedList.h, and Node.cpp make up the LinkedList, and test.cpp is where I run my program to test the LinkedList.

LinkedList.cpp

//t LinkedList.cpp
//--linking
#include "LinkedList.h"
#include <iostream>
using namespace std;

//--consrs.
template<typename E>
LinkedList<E>::LinkedList(){
    head = nullptr;
    size = 0;
}

LinkedList.h

//t LinkedList.h
//--include deff.
#ifndef LinkedList_h
#define LinkedList_h

//--linking
#include "Node.cpp"

//--class
template<typename E>
class LinkedList{
public:

    //--consrs.
    LinkedList();
};

#endif

Node.cpp

#include "LinkedList.h"
//t Node.cpp
//--class
template<typename E>
class Node{
public:
    friend class LinkedList<E>;
};

test.cpp

//t test.cpp
//--linking
#include "LinkedList.cpp"
#include <iostream>
using namespace std;

//--main
int main(){
    LinkedList<int> myList;
}

Note: I am new to stack overflow, so my apologies if I did not explain something right.


Solution

  • The definition for the node template is in the source (.cpp) file. Template definitions should be in the header file.

    See the following: Storing C++ template function definitions in a .CPP file