16

Ok guys... I have following class

#include <functional>

template <typename TValue, typename TPred = std::less<TValue>>
class BinarySearchTree {
    struct TNode {
        TValue value;
        TNode *pLeft;
        TNode *pRight;
    };
public:
    BinarySearchTree();
    ~BinarySearchTree();

    . . .
private:
    TNode *pRoot;

     . . .
};

then in my .cpp file i defined the ctor/dtor like this:

template <typename TValue, typename TPred>
BinarySearchTree<TValue, TPred>::BinarySearchTree() : pRoot(0) {}

template <typename TValue, typename TPred>
BinarySearchTree<TValue, TPred>::~BinarySearchTree() {
    Flush(pRoot);
}

my main function:

int main() {    
    BinarySearchTree<int> obj1;
    return 0;
}

and i get following linkage error:

public: __thiscall BinarySearchTree<int,struct std::less<int>>::BinarySearchTree<int,struct std::less<int> >(void)

i tried to put the constructor definition into the header file and i get no error. only if i try to define it in the cpp file.

xlw12
  • 761
  • 1
  • 7
  • 16
  • 6
    The answer to your question is [here](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) - sorry, wrong link in the close vote – Andy Prowl Jun 03 '13 at 18:53

2 Answers2

24

Don't define templates in the cpp file, but put the implementation of the functions in the header file and leave your main function as it is. Templates get inlined by default. Therefore they are not visible to the linker. And the file that contains main() cannot see the definition of the templates. Hence the error.

Ralph Tandetzky
  • 22,780
  • 11
  • 73
  • 120
0

leave space at last and try. it might be taken as shift left operator!

template <typename TValue, typename TPred = std::less<TValue> >
Dineshkumar
  • 4,165
  • 5
  • 29
  • 43