Problem Instantiating Template Class in C++

Nibbie
Posts: 1
Joined: 2008.10
Post: #1
Hey there guys,

I am having some trouble creating an instance of a C++ template that I wrote.
It sounds simple and I have no idea why this is happening, but when i try to do:

Code:
    using namespace DataStructure;
    
    BinarySearchTree<int> testTree;

I get this error from Xcode:

Code:
"DataStructure::BinarySearchTree<int>::~BinarySearchTree()", referenced from:
      _main in main.o
  "DataStructure::BinarySearchTree<int>::BinarySearchTree()", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

It looks like it can't find the constructor/destructor when it gets created, although i can't imagine why, because it definately exists.

Here is a sample of my code incase anyone can help:

from BinarySearchTree.h:
Code:
namespace DataStructure
{
    template <typename Type>
    class BinarySearchTree : public DataStructure::BinaryTree<Type>::BinaryTree
    {
    public:
        BinarySearchTree();
        ~BinarySearchTree();
    
        bool Search        ( const Type &searchItem ) const;
        void Insert        ( const Type &insertItem );
        void DeleteNode    ( const Type &deleteNode );
        
    private:
        void deleteFromTree( BSNode<Type> *&p );
    };
}

from BinarySearchTree.cpp:
Code:
template <typename Type>
DataStructure::BinarySearchTree<Type>::BinarySearchTree()
{
    
}

template <typename Type>
DataStructure::BinarySearchTree<Type>::~BinarySearchTree()
{

}

The help would be greatly appreciated.
This has been driving me insane for hours.
Thanks everyone Wink
Quote this message in a reply
Member
Posts: 45
Joined: 2006.07
Post: #2
For templated classes, don't use a separate .cpp file. Put it *all* in the header. When you compile the .cpp, it doesn't instantiate the template for any particular class unless you tell it to by adding the line
Code:
template class DataStructure::BinarySearcyTree<int>;
at the end of the file. If you know you only want to instantiate the template for a few specific classes, this is okay, but generally you want everything in the header file.
Quote this message in a reply
Member
Posts: 241
Joined: 2008.07
Post: #3
Trivia: there's actually a keyword that works on some compilers (none mainstream) export, which somehow allows you to separate the implementation of a template class.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  C++ template problem anthony 9 5,309 Feb 7, 2007 10:04 AM
Last Post: anthony