Creating a template class object using the template constructor

I had a problem creating a class object from a template class, in which I need a constructor, which should also be a template and take a parameter when creating the object. However, when I try to create an object, I get an error message indicating that I am referring to something that does not exist.

Here is my code:

using namespace std; #include <cstdlib> template <class Node_Type> class BinaryTree { public: BinaryTree(Node_Type); BinaryTree(Node_Type, Node_Type); BinaryTree(Node_Type, Node_Type, Node_Type); bool isEmpty(); Node_Type info(); Node_Type inOrder(); Node_Type preOrder(); Node_Type postOrder(); private: struct Tree_Node { Node_Type Node_Info; BinaryTree<Node_Type> *left; BinaryTree<Node_Type> *right; }; Tree_Node *root; }; #endif 

and my .cpp:

 template <class Node_Type> BinaryTree<Node_Type>::BinaryTree(Node_Type rootNode) { root = rootNode; root->left = NULL; root->right = NULL; } 

There's more to .cpp, but these are just other function members that don't matter. My constructor shown above is something that I cannot work with.

Basically, I'm trying to declare my object with a call:

 BinaryTree<char> node('a'); 

but when I try this, I get an error message:

 undefined reference to `BinaryTree<char>::BinaryTree(char)' 

I have been trying to figure this out for two days now. I have searched for every topic that I can think of, and read countless examples in Qaru and other sources without any help. Can someone explain what my problem is? I know how to make my project, and I would finish if the syntax weren’t so funny in C ++. Thanks in advance!

+6
source share
3 answers

The template code must be visible at instantiation, which means that the function definition must also be in the header.

+10
source

Decision. You cannot separate template implementations from the header file. Just don't use the cpp file and put the definition in your header file (.h file).

Why? This is because cpp files can become precompiled sources, and templates can become compilation objects; therefore, the compiler cannot decide which type to use if not specified. So just put all your undefined templates in the .h header file.

+6
source

You can force an instance of the template in another cpp file.

 BinaryTree<char>; BinaryTree<int>; BinaryTree<double>; 

Thus, all functions do not have to be in the header files. Some use the .inl extension for files with template implementations. Therefore, the .inl file is needed only when the instance does not exist.

+2
source

Source: https://habr.com/ru/post/954098/


All Articles