2009-11-07 98 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