Reputation: 778
I'm trying to create a tree class in c++ and i'm not sure how should I use the templates when I am using recursion.
for example I have the following function:
template <typename Data>
void destroyTree(typename AVLTree<Data>::Node* element) {
if(!element) {
return;
}
destroyTree(element->getLeft());
destroyTree(element->getRight());
delete element;
}
or should it be:
template <typename Data>
void destroyTree(typename AVLTree<Data>::Node* element) {
if(!element) {
return;
}
destroyTree<Data>(element->getLeft());
destroyTree<Data>(element->getRight());
delete element;
}
then if I call it suppose from the following function:
template <typename Data>
void AVLTree<Data>::function() {
destroyTree(root);
}
or:
template <typename Data>
void AVLTree<Data>::function() {
destroyTree<Data>(root);
}
I've tried to combine most of the possibilities above but I always get an error.
usually it's a non matching function for call to
If someone has some experience with that issue please help me.
Thank you.
If I use Nawaz's suggestion I get the following error:
Internal Builder is used for build ** g++ -O0 -g3 -Wall -c -fmessage-length=0 -oAVLTest.o ..\AVLTest.cpp g++ -oAVLTree.exe AVLTest.o AVLTest.o: In function ZN15Data_Structures7AVLTreeIiE4Node7getLeftEv': C:/Users/Alex/workspace/AVLTree/Debug/../AVLTree.h:(.text$_ZN15Data_Structures11destroyTreeIiEEvPNS_7AVLTreeIT_E4NodeE[void Data_Structures::destroyTree(Data_Structures::AVLTree::Node*)]+0x47): undefined reference toData_Structures::AVLTree::Node::~Node()' collect2: ld returned 1 exit status Build error occurred, build is stopped Time consumed: 532 ms.
what can I do with that?
all relevant code is here.
Upvotes: 4
Views: 155
Reputation: 361362
This is correct:
//in the first case
destroyTree<Data>(element->getLeft());
destroyTree<Data>(element->getRight());
//in the second case
destroyTree<Data>(root);
That is, you have to specify the template argument, as it cannot be deduced by the compiler from the function argument because it is a non-deducible context.
Upvotes: 5