Problem Instantiating Template Class in C++

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:

    using namespace DataStructure;
    BinarySearchTree<int> testTree;

I get this error from Xcode:

"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:
namespace DataStructure
    template <typename Type>
    class BinarySearchTree : public DataStructure::BinaryTree<Type>::BinaryTree
        bool Search        ( const Type &searchItem ) const;
        void Insert        ( const Type &insertItem );
        void DeleteNode    ( const Type &deleteNode );
        void deleteFromTree( BSNode<Type> *&p );

from BinarySearchTree.cpp:
template <typename Type>

template <typename Type>


The help would be greatly appreciated.
This has been driving me insane for hours.
Thanks everyone Wink
Quote this message in a reply
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
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
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
  Forcing template parameter type Fenris 4 4,968 Jan 4, 2008 07:03 AM
Last Post: TomorrowPlusX
  C++ template problem anthony 9 10,004 Feb 7, 2007 10:04 AM
Last Post: anthony