Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templates and nested classes/structures

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.

like image 783
Rohan Prabhu Avatar asked Nov 07 '09 19:11

Rohan Prabhu


People also ask

What is the difference between class template and template class?

A class template is a template that is used to generate classes whereas a template class is a class that is produced by a template.

What are templates in data structure?

A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.

What is a template class?

Definition. As per the standard definition, a template class in C++ is a class that allows the programmer to operate with generic data types. This allows the class to be used on many different data types as per the requirements without the need of being re-written for each type.

Can class template be nested?

Member templates that are classes are referred to as nested class templates. Member templates that are functions are discussed in Member Function Templates. Nested class templates are declared as class templates inside the scope of the outer class. They can be defined inside or outside of the enclosing class.


1 Answers

You need to tell the compiler that node is a type using the keyword typename.Otherwise it will think node as a static variable in class list. Add typename whenever you use node as a type in your implementation of list.

like image 92
Ponting Avatar answered Oct 04 '22 19:10

Ponting