iDevGames Forums
Problem Instantiating Template Class in C++ - Printable Version

+- iDevGames Forums (http://www.idevgames.com/forums)
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Programming Languages & Scripting (/forum-8.html)
+--- Thread: Problem Instantiating Template Class in C++ (/thread-2140.html)



Problem Instantiating Template Class in C++ - brockwoolf - Nov 17, 2008 06:41 AM

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


Problem Instantiating Template Class in C++ - mattz - Nov 17, 2008 09:19 AM

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.


Problem Instantiating Template Class in C++ - bmantzey - Jan 13, 2009 11:54 PM

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.