Need typename error (template related error)

2020-05-04 10:06发布

I have a class called node inside another class which is templated. Some of the methods of class Node returns Node pointer. This is an excerpt of how I implemented

 template <typename T>
 class myClass{
 ....
     class Node{
         Node* getNodePointer();
         ...
     }
 }     
 ... 
 template <typename T>
 myClass<T>::Node* myClass<T>::Node::getNext()  
 { return next;  }

When I compile above code, I get this error " myClass.h:138:1: error: need ‘typename’ before ‘myClass::Node’ because ‘myClass’ is a dependent scope". How do I fix this problem? Many thanks

标签: c++ templates
2条回答
该账号已被封号
2楼-- · 2020-05-04 10:35

To clarify, the compiler has no idea that myClass<T>::Node is now or ever will be a type. Think of it this way:

template <typename T>
class A
{
public:
    typedef T value_type;
};

template <typename T>
class B
{
public:
   typename A<T>::value_type x;
};

template <> A<int> { public: static int value_type=10;}

You have to make the promise to the compiler that the type is a typename. It defaults to assuming that it is a value.

查看更多
Summer. ? 凉城
3楼-- · 2020-05-04 10:41

How do I fix this problem?

The compiler's error message s pretty clear about this point:
To use nested classes, structs or typedefinitions from a template class you need to add the typename keyword to tell the compiler you want to use it as a type:

   template <typename T>
   typename myClass<T>::Node* myClass<T>::Node::getNext()  { // ...
// ^^^^^^^^ << Add typename keyword
查看更多
登录 后发表回答