C++ compile error with templates
I have this function:
template <typename T>
List<T>::ListNode *List<T>::find(int index) const
{
if ( (index < 1) || (index > getLength()) )
return NULL;
el开发者_StackOverflow社区se
{
ListNode *cur = head;
for (int skip = 1; skip < index; ++skip)
cur = cur->next;
return cur;
}
}
That is giving me these two errors, each on the second line:
expected constructor, destructor, or type conversion before '*' token
expected `;' before '*' token
All my other methods that use templates work just fine. I think the problem is that my syntax where I am calling my ListNode struct is wrong. I had this working without templates earlier and now I'm trying to implement it with templates and I am getting these errors.
It should be
template <typename T>
typename List<T>::ListNode *List<T>::find(int index) const
// ...
typename
tells the compiler that List<T>::ListNode
represents a type. When inside a template, there is a parsing ambiguity when ::
is encountered. You therefore have to use the typename
keyword when whatever follows ::
is a type.
精彩评论