如何编写一个返回仅存在于类中的类型的成员函数? [英] How do I write a member function that returns a type that only exists in the class?
问题描述
我实际上是在C ++中实现一个双向链接列表.
I'm actually implementing a doubly-linked list in C++.
这是各种MWE:
namespace mynamespace {
template <typename T>
class List {
public:
List();
void prepend(T);
void append(T);
void remove(T);
private:
struct Node {
T value_;
Node * prev_;
Node * next_;
};
private:
Node * find(T); // <-- THIS IS MY PROBLEM
private:
Node * head_;
Node * tail_;
};
}
我想创建该函数的原因是因为我认为如果可以使用这样的函数遍历列表,直到找到给定的元素,这将非常方便(我需要对仍然是remove()
函数)
The reason I'd like to create that function is because I figured it'd be handy if I could traverse the list with a function like that until I find a given element (I'll need to do the same with the remove()
function anyways)
但是我如何在class
定义之外定义该函数?
But how do I define that function outside the class
definition?
由于Node
是List
类的私有成员,因此不起作用:
Since Node
is a private member of the List
class, this is not working:
template <typename T>
Node * List<T>::find(T val)
{
// stuff
}
我想在Node
在那里有意义...这是正确的方法吗?即使是这样,我想也必须有一种方法可以定义我要尝试的功能.
I suppose defining the function inside the class
definition would work, because Node
makes sense there... Would that be the proper way? Even if so, I suppose there must be a way to define the function the way I'm trying to...
推荐答案
由于
Node
是List
类的私有成员,因此不起作用:
Since
Node
is a private member of theList
class, this is not working:
实际上,这是不正确的.这并不是因为Node
是私有的,而是因为Node
嵌套在List
内部. Node
类的名称不是Node
,而是List<T>::Node
.但是,由于Node
取决于T
,因此您必须编写typename List<T>::Node
,否则编译器假定List<T>::Node
是值而不是类型.有关更多信息,请参见此问题.
Actually, that's not correct. It's not failing because Node
is private, but because Node
is nested inside of List
. The name of the Node
class isn't Node
, it's List<T>::Node
. However, since Node
depends on T
, you have to write typename List<T>::Node
, otherwise the compiler assumes that List<T>::Node
is a value rather than a type. See this question for more information.
简而言之,将其替换:
template <typename T>
Node * List<T>::find(T val)
与此:
template <typename T>
typename List<T>::Node * List<T>::find(T val)
或者,如StoryTeller所述,如果您在List<T>
类的上下文中,则可以只使用Node
.您可以通过使用尾随返回类型来获得此上下文:
Alternatively, as StoryTeller noted, if you are in the context of the List<T>
class, you can just use Node
. You can get in this context by using a trailing return type:
template <typename T>
auto List<T>::find(T val) -> Node *
这篇关于如何编写一个返回仅存在于类中的类型的成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!