模板和嵌套类/结构
我有一个简单的容器:
template <class nodeType> list {
public:
struct node {
nodeType info;
node* next;
};
//...
};
现在,有一个名为 _search
的函数,它搜索列表并返回对匹配节点的引用。现在,当我提到函数的返回类型时,我认为它应该是 list
。这是对的吗?当我内联定义函数时,它工作得很好:
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
或其他内容。该错误与此类似。我目前没有可以测试它的机器。
真诚感谢任何帮助。
I have a simple container :
template <class nodeType> list {
public:
struct node {
nodeType info;
node* next;
};
//...
};
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
}
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.
Any help is sincerely appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为
node
是一个依赖类型。您需要按如下方式编写签名(请注意,为了清楚起见,我将其分成两行)请注意
typename
关键字的使用。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)Note the use of the
typename
keyword.您需要使用关键字
typename
告诉编译器node
是一个类型。否则它会认为 Node 是中的
。每当您在列表实现中使用节点作为类型时,请添加static
变量类列表typename
。You need to tell the compiler that
node
is a type using the keywordtypename
.Otherwise it will think node as astatic
variable inclass list
. Addtypename
whenever you use node as a type in your implementation of list.