Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Nested class in class template declaration

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?

like image 201
JamesLens Avatar asked May 17 '15 13:05

JamesLens


People also ask

What are nested class declarations in C++?

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]

What is a nested class in Java?

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.

How to declare a class within another class?

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.

What is the difference between nested class and enclosing 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.


1 Answers

look here

template <typename T>
std::shared_ptr<typename LinkedList<T>::Node> LinkedList<T>::listSearch(const T &input) { ... }
like image 76
Xiaotian Pei Avatar answered Oct 10 '22 17:10

Xiaotian Pei