Reputation: 1883
I'm trying to implement my own Set template, and have issues with trying to do a breadth- first search using my Queue template that works independently.
The weird part is that I get this error in my Set template when trying to compile. Why can't it convert from one pointer to a different one that is the same data type?
error C2440: '=' : cannot convert from 'Set<T>::Node<T> *' to 'Set<T>::Node<T> *'
with
[
T=std::string
]
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
c:\users\programming\Set\Set.h(96) : while compiling class template member function 'void Set<T>::print(Set<T>::Node<T> *)'
with
[
T=std::string
]
c:\users\programming\Set\main.cpp(13) : see reference to class template instantiation 'Set<T>' being compiled
with
[
T=std::string
]
Queue Class Template
template <typename T>
class Queue
...
T* front()
{
if (first != NULL)
return first->item;
else
return NULL;
}
Set Class Template
template <typename T>
Class Set
...
Queue<Node<T> *> q;
void print(Node<T> *p)
{
q.push(p);
while (p != NULL)
{
cout << p->item << "(" << p->height << ") ";
if (p->left != NULL)
q.push(p->left);
if (p->right != NULL)
q.push(p->right);
if (!q.size())
{
// Error is at this line
p = q.front();
q.pop();
}
else
p = NULL;
}
cout << endl;
}
Upvotes: 1
Views: 1723
Reputation: 32520
Your Queue
class is instantiated with a Node<T>*
type already ... you are then attempting to return a pointer to a type T
from your Queue<T>::front
method. If you are instantating your Queue<T>
class with T=Node<T>*
, then you only need to return a type T
from your front
method, not a T*
. So change your front
method signature to the following:
template <typename T>
class Queue
...
T front()
{
if (first != NULL)
return first->item;
else
return NULL;
}
Now this could cause you a bunch of problems if T
was not a pointer type ... therefore you may want to create a specialization of your Queue<T>::front
method for cases where T
is already a pointer type. For instance:
//pointer-type specialization
template<typename T>
T Queue<T*>::front()
{
if (first != NULL)
return first->item;
else
return NULL;
}
//non-specialized version where T is not a pointer-type
template<typename T>
T* Queue<T>::front()
{
if (first != NULL)
return &(first->item);
else
return NULL;
}
Upvotes: 2