模板和嵌套类/结构

Roh*_*bhu 10 c++ containers templates data-structures

我有一个简单的容器:

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

    //...
};
Run Code Online (Sandbox Code Playgroud)

现在,有一个函数被调用_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;
        }
};
Run Code Online (Sandbox Code Playgroud)

但是,如果我在课外定义函数,

template <class nodeType> list<nodeType>::node* list<nodeType>::_search() {
    //function
}
Run Code Online (Sandbox Code Playgroud)

它不起作用.编译器给出了错误说法Expected constructor before list<nodeType>::_search或其他内容.错误与此类似.我目前没有可以测试它的机器.

任何帮助都是真诚的感谢.

rlb*_*ond 24

那是因为node是一种依赖类型.您需要按如下方式编写签名(请注意,为了清楚起见,我已将其分为2行)

template <class nodeType> 
typename list<nodeType>::node* list<nodeType>::_search() 
{
    //function
}
Run Code Online (Sandbox Code Playgroud)

请注意typename关键字的使用.


Pon*_*ing 9

您需要告诉编译器node使用关键字的类型.typename否则,它会将节点视为static变量class list.添加typename只要您使用节点作为您的实现列表的类型.