Declaring a structure in a template class, undefined for member functions

I'm currently trying to implement a sorting algorithm in a list template class using node structures private to the list class. I use several private recursive functions that return a pointer to a node type, which causes g ++ to give me a declaration error. Here is an example of what I have -

template<class T> class SList { private: struct NODE { T* elem; NODE* next; } *_head, *_tail; NODE* sort(NODE* node); public: //other declarations... } template<class T> NODE* SList<T>::sort(NODE* node) //Error: 'NODE' does not name a type { //sorting algorithm } 

Is this a C ++ limitation or am I missing something?

+4
source share
3 answers

Since Node is an inner class, you need to tell the compiler where the Node definition comes from.

In addition, the definition of Node changes depending on which parameter of the SList template (this is a dependent type)

So you should explicitly reference Node as such:

 template<class T> typename SList<T>::NODE* SList<T>::sort(typename SList<T>::NODE* node) { //sorting algorithm } 
  • Pay attention to typename , because Node is a dependent type (depends on the type of SList )
  • Pay attention to SList<T>::Node , because Node is a dependent type on SList .
+10
source

Below works fine:

 template<class T> typename SList<T>::NODE* SList<T>::sort(typename SList<T>::NODE* node) ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^ 

Is this a C ++ limitation

No. Because there cannot be any structure / type named NODE outside the scope of SList<> ; so this is actually an object that C ++ provides you with, where you can have the same name in different areas.

"Why do I need the typename keyword" can be found here .

+2
source

The type you want to refer to is within the SList, so you should reference it as such:

 template<class T> typename SList<T>::NODE* SList<T>::sort(typename SList<T>::NODE* node); 
+1
source

All Articles