I'm currently working with nodes of type template, I run into a problem when I compare those nodes with data from a normal class. The 2 data types that aren't matching up is the line root->data = item;
root
is Node<string> *TreeParser::root
, where as item
is const Node <string> &
. When looking at previous work where both classes are type template this works. However, when I change the class to a nontemplate type this code no longer works. How can I get these 2 different types of data to talk to each other with out changing my class to type template. Here is my example code:
template <typename T>
struct Node {
T data;
Node* lLink;
Node* rLink;
};
class TreeParser{
public:
void insert(const Node<string>& item);
private:
Node<string>* root{ nullptr };
};
void TreeParser::insert(const Node<string>& item){
if (root == nullptr){
root = new Node<string>();
root->data = item;
return;
}
else
//do something
}
root->data = item;
This root
is a pointer to a Node<string>
root = new Node<string>();
So, pop quiz time: what is root->data
. The right answer is, of course, it's a std::string
. The template parameter is std::string
, so with the template declaring a:
T data;
With T
being the aforementioned std::string
, we there conclude that in this statement:
root->data = item;
The root->data
portion is a std::string
. Now the next item for discussion is what exactly is the item
here, well it is declared as:
const Node<string>& item
So, therefore, your item
is a Node<string>
.
So, in summary:
root->data = item;
attempts to assign a Node<String>
to a string
.
That, of course, is not going to work. The only thing that can be assigned to a std::string
would be another std::string
, or a const char *
, perhaps, or a few other things that are not important here.
Your likely intention is:
root->data = item.data;
But, any place you can find some other std::string
will work equally well here.
In your code root->data
is a string
whereas item
is a Node<string>
reference. These are obviously incompatible types. If you really want to avoid templating TreeParser
you should use the copy or move constructor of Node
for the creation of root
. Something like: root = new Node<string>(item);
Oh yes, and to forgo the usual comment, use unique_ptr
or shared_ptr
instead of a naked pointer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.