user2814492
user2814492

Reputation: 11

syntax error when writing find function for List

I'm running into a syntax error which I am sure is correct:

expected constructor, destructor, or type conversion before '*' token
expected `;' before '*' token 

ListP.h

#ifndef LISTP_H
#define LISTP_H
template <typename T>
class ListP
{
private:
    struct ListNode
    {
        T item;
        ListNode* next;
    };

    ListNode* find(int index) const;
    ......
}

ListP.cpp

template <typename T>
ListP<T>::ListNode* ListP<T>::find(int index) const
{
 ......
}

The error occurs at the line.

ListP<T>::ListNode* ListP<T>::find(int index) const

Upvotes: 1

Views: 81

Answers (3)

Walter
Walter

Reputation: 45434

1 your code is incorrect, you must add typename to disambiguate ListNode as a type (rather than a static data member):

template <typename T>
typename ListP<T>::ListNode* ListP<T>::find(int index) const
{
 ......
}

2 As you implement your template in a source file, make sure all implementations actually used in your code (all files including the header) are actually instantinated in List.cpp. You can ensure that using static_assert, such that code using other implementations fails to compile.

Upvotes: 0

Jesse Good
Jesse Good

Reputation: 52365

Looks like you have 3 issues:

Missing semicolon after class definition:

};

Missing typename:

typename ListP<T>::ListNode* ListP<T>::find(int index) const

See Where and why do I have to put the “template” and “typename” keywords? for more info.

and you should implement templates in header file

See Why can templates only be implemented in the header file? for a good explanation.

Upvotes: 5

anhoppe
anhoppe

Reputation: 4497

Template functions are usually implemented in the header file, don't put the definition in the cpp

Upvotes: 0

Related Questions