模板和嵌套类/结构 [英] Templates and nested classes/structures

查看:90
本文介绍了模板和嵌套类/结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的容器:

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

    //...
};

现在,有一个函数 _search 它搜索列表并返回对匹配的节点的引用。现在,当我指的是函数的返回类型时,我认为应该是 list< nodeType> :: node * 。这是正确的吗?当我定义函数inline时,它工作完美:

Now, there is a function called _search which searches the list and returns a reference to the node which matched. Now, when I am referring to the return-type of the function, I think it should be list<nodeType>::node*. Is this right? When I define the function inline, it works perfectly:

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

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

但是,如果我定义类外的函数,

But, if I define the function outside the class,

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

它不工作。编译器给出一个错误,在列表< nodeType> :: _ search 或某事之前说出 Expected构造函数。错误是类似的。我现在没有机器可以测试它。

it doesn't work. The compiler gives an error saying Expected constructor before list<nodeType>::_search or something. The error is something similar to this. I don't have a machine on which I can test it currently.

任何帮助真的很感激。

推荐答案

这是因为节点是一个依赖类型。您需要写如下的签名(注意,为了清楚起见我已将它分成两行)

that's because node is a dependent type. You need to write the signature as follows (note that I have broken it into 2 lines for clarity)

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

请注意使用 typename 关键字。

这篇关于模板和嵌套类/结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆