I'm actually implementing a doubly-linked list in C++.
Here's a MWE of sorts:
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_;
};
}
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)
But how do I define that function outside the class
definition?
Since Node
is a private member of the List
class, this is not working:
template <typename T>
Node * List<T>::find(T val)
{
// stuff
}
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...
List<T>::find
to tell the compiler wherefind
is you need to do the same thing toNode
.typename
(I tried what you and @NathanOliver initally said, but I thought that was wrong too, because w/o thetypename
, I got errors). Would you please add this as an answer so that I can mark it as a solution? Also, would you explain why I need thetypename
?const T&
arguments rather thanT
, so in caseT
is something likestd::string
there won't be an unnecessary copy. (A possible exception would be "insert" type operations like yourprepend
orappend
where you can use a pass-by-value and then move the parameter into the container, in order to avoid having to write separate copyprepend(const T&)
and moveprepend(T&&)
versions of the method.)