Weekly programming – Templated Linked List (v46)
|
This weekend I created a linked list class using tutorials from “Paul Programming” on Youtube (link). This linked list was locked to integer variables. This tuesday we had a lecture on template programming and I set out to modify my linked list into a templated one. Before I got it working I had problems with these things; I started by changing all functions IN the class by adding template to them. THEN I added the template to the entire LinkedList class. I got errors that I didn’t understand and the compiler showed errors at places that weren’t relevant. The problem was me adding template to the functions IN the class, I removed them and it seemed to work. It seemed to work until I tried to compile. My next problem was defining functions (even the constructor and destructor of the class) in the .cpp-file. I found information on this from stackoverflow (link). Templates are compiled at “compile-time”, not “link-time”. Apparently the header and .cpp-files does not know of each other in “compile-time” and the functions needs to be defined in the header-file when creating a templated class. So I placed all definitions in the header-file and everything works like a charm. My templated linked list can be found on BitBucket using this link. Update: It is possible to separate the definition and declaration in different files by adding an include to a second file at the end of the header file. The file ending of the second file should be something other than .cpp. Suggested file endings are: .tpp or .inl. I tried this but VS intellisense didn’t make the connection between the files so I didn’t like this method. However, I did make one change. It’s a small one. I separated the definitions and declarations in the class while still having them both in the header file. When doing this I encountered another problem when having a method returning a Node (a struct within the template class). When defining the method you need to add “typename” before the return type. I have created a Binary Search Tree as well, check it out in the BitBucket link! |


