1

独自の Set テンプレートを実装しようとしていますが、独立して動作する Queue テンプレートを使用して幅優先検索を実行しようとすると問題が発生します。

奇妙な部分は、コンパイルしようとすると Set テンプレートでこのエラーが発生することです。あるポインターから同じデータ型の別のポインターに変換できないのはなぜですか?

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
      ]

キュー クラス テンプレート

template <typename T>
class Queue
...
T* front()
{
    if (first != NULL)
        return first->item;
    else
        return NULL;
}

クラス テンプレートの設定

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;
}
4

1 に答える 1

2

QueueクラスはNode<T>*すでに型でインスタンス化されています...その後、メソッドTから型へのポインタを返そうとしていますQueue<T>::frontQueue<T>を使用してクラスをインスタンス化する場合は、メソッドからT=Node<T>*型を返すだけでよく、 . したがって、メソッドのシグネチャを次のように変更します。TfrontT*front

template <typename T>
class Queue
...
T front()
{
    if (first != NULL)
        return first->item;
    else
        return NULL;
}

がポインター型でない場合、これにより多くの問題が発生する可能性がありますT...したがって、既にポインター型Queue<T>::frontである場合にメソッドの特殊化を作成することができます。T例えば:

//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;
}
于 2012-06-04T14:25:13.873 に答える