Friday 8 February 2019

c++ - Template class constructor




Ok guys...
I have following class




#include 

template >
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 
BinarySearchTree::BinarySearchTree() : pRoot(0) {}

template
BinarySearchTree::~BinarySearchTree() {
Flush(pRoot);
}



my main function:



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



and i get following linkage error:



public: __thiscall BinarySearchTree>::BinarySearchTree >(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.


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...