1

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
arserbin3
  • 6,010
  • 8
  • 36
  • 52

3 Answers3

5

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.

Community
  • 1
  • 1
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • "*you should implement templates in header file*" Not always and not necessarily (though in case of a general-purpose list, it is the only way). As general advise, however, this is unacceptable – Walter Sep 25 '13 at 09:47
  • @Walter: Why is it unacceptable? There are other ways, but implementing them in the header file is the most common. – Jesse Good Sep 25 '13 at 09:50
0

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.

Walter
  • 44,150
  • 20
  • 113
  • 196
0

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

anhoppe
  • 4,287
  • 3
  • 46
  • 58
  • Wrong. I often implement templates in .cpp files. This is very useful, as it reduces compilation time (of other files) substantially. It is only possible, if the total number of sensible instantinations is small. – Walter Sep 25 '13 at 09:42
  • Interesting. I thought the definition has to be available at compile time when a template instance is needed anywhere and though the implementation has to be in the header. Maybe implementing it in the cpp is only possible when the function is only used in that module? But I have to admit that my template knwoledge is rather limited... – anhoppe Sep 25 '13 at 09:46
  • No, it is generally possible. The linker will try to find the instantination. If it cannot find it, only then an error will occur. – Walter Sep 25 '13 at 09:48