2009-11-07 96 views
8

我有一個簡單的容器:模板和嵌套類/結構

template <class nodeType> list { 
    public: 
     struct node { 
      nodeType info; 
      node* next; 
     }; 

    //... 
}; 

現在,有一種叫做_search函數用於搜索該列表並返回到其相匹配的節點的引用。現在,當我指的是函數的返回類型時,我認爲它應該是list<nodeType>::node*。這是正確的嗎?當我定義函數內聯,它完美的作品:

template <class nodeType> list { 
    public: 
     struct node { 
      nodeType info; 
      node* next; 
     }; 

     node* _search { 
      node* temp; 
      // search for the node 
      return temp; 
     } 
}; 

但是,如果我定義類外的函數,

template <class nodeType> list<nodeType>::node* list<nodeType>::_search() { 
    //function 
} 

這是行不通的。編譯器給出一個錯誤,說Expected constructor before list<nodeType>::_search什麼的。錯誤與此類似。我目前沒有可以測試的機器。

任何幫助,真誠讚賞。

回答

21

那是因爲node是一個依賴類型。你需要如下(注意,我已經打破成2線清晰度)

template <class nodeType> 
typename list<nodeType>::node* list<nodeType>::_search() 
{ 
    //function 
} 

注意使用typename關鍵字寫的簽名。

+1

更多,非常geeky,細節可以在C++ FAQ精簡版中找到:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18 – 2009-11-07 19:18:04

+0

非常感謝您的幫助..它現在完美運作。再次感謝.. – 2009-11-13 14:14:22

+0

常見問題解答的更新鏈接:https://isocpp.org/wiki/faq/templates#dependent-name-lookup-types – Ashe 2017-03-01 03:05:55

6

你需要告訴編譯器node是使用關鍵字typename一個類型。否則它會認爲節點在class list一個static變量。只要您在實施列表中使用節點作爲類型,就添加typename