I'm attempting to write a C++11 linked list implementation, with the linked list being a template class and its node being a nested class as follows:
template <typename T>
class LinkedList {
public:
class Node;
std::shared_ptr<Node> listSearch(const T &input) const;
private:
std::shared_ptr<Node> head;
std::shared_ptr<Node> tail;
};
template <typename T>
class LinkedList<T>::Node {
private:
T data;
std::shared_ptr<Node> next;
}
I am assuming that the class Node is not a template in itself, but when LinkedList gets instantiated it creates the Node class as well.
When I attempt to define the listSearch function as follows, I get an error: "template argument for template type parameter must be a type; did you forget 'typename'?". Can someone explain what is wrong?
template <typename T>
std::shared_ptr<LinkedList<T>::Node> LinkedList<T>::listSearch(const T &input) { ... }
Edit:
Ok, so I recompiled with gcc and the error message was clearer. It wants the following:
std::shared_ptr<typename LinkedList<T>::Node> LinkedList<T>::listSearch(const T &input) const { ... }
Why is the typename necessary before LinkedList::Node? Isn't it obvious that it's a type?
Nested class declarations obey member access specifiers, a private member class cannot be named outside the scope of the enclosing class, although objects of that class may be manipulated: C++11 standard (ISO/IEC 14882:2011): 9.7 Nested class declarations [class.nest]
Nested Class Declarations. A class can be declared within the scope of another class. Such a class is called a "nested class.". Nested classes are considered to be within the scope of the enclosing class and are available for use within that scope.
A declaration of a class/struct or union may appear in within another class. Such declaration declares a nested class The name of the nested class exists in the scope of the enclosing class, and name lookup from a member function of a nested class visits the scope of the enclosing class after examining the scope of the nested class.
The nested class is also a member variable of the enclosing class and has the same access rights as the other members. However, the member functions of the enclosing class have no special access to the members of a nested class.
look here
template <typename T>
std::shared_ptr<typename LinkedList<T>::Node> LinkedList<T>::listSearch(const T &input) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With