0

Hi I tried to create a List Class. But in order to have a variation of list class, I am using template to store value in item variable.

Below is in "List.h"

template <class ListItemType>
    class List
    {
        public:
            .........
            .........

        private:
            struct ListNode
            {
                ListItemType item;
                ListNode    *next; 
            };

        int size; 
        ListNode *head;
        ListNode *find(int index) const;
    };

Then how do I create the implementation of "ListNode *find(int index) const" function in List.cpp?

I tried to use

template <class ListItemType>
    List<ListItemType>::ListNode *List<ListItemType>::find(int index) const
    {
        ........
    }

But there is an error saying "error: need 'typename' before 'List::ListNode' because 'List' is a dependent scope"

Do you know how do I implement "ListNode *find(int index) const" in List.cpp?

This is my first time using template, I am a bit confuse. Thanks

muhihsan
  • 2,250
  • 6
  • 27
  • 42
  • 6
    The error is quite clear (not usually the case with templates). You need `typename List::ListNode `. – juanchopanza Aug 18 '13 at 06:47
  • @juanchopanza oke thanks, and let say I declare the list as a pointer, assign it to an instance, and I want that template to have integer value. And how do I do that? – muhihsan Aug 18 '13 at 06:57
  • 2
    Why would you want a pointer? Just create an object: `List my_list;` – juanchopanza Aug 18 '13 at 06:59
  • @juanchopanza ok. and why, when I tried to declare it in another class (List my_list;) i created. When that class constructor is called there is an error saying "Undefined reference to 'List::List()'" – muhihsan Aug 18 '13 at 07:08
  • 2
    That is because the linker cannot find the implementation of `List`'s default constructor. Make sure all the implementations are in the header file. – juanchopanza Aug 18 '13 at 07:10
  • @juanchopanza when we declare the implementation in header files, do i need to also specify template or typename or just simply "List();"? – muhihsan Aug 18 '13 at 07:27
  • @IhsanMuhammad if its inside the class decl, just `List() { ...code...}` will be adequate. If it is outside the class decl, then you need to fully qualify it, including the template characteristics. – WhozCraig Aug 18 '13 at 08:02

1 Answers1

0

Because ListNode is a name of a type within your templated class you need to write:

typename List<ListItemType>::ListNode

Also, the implementation of your template probably needs to be visible to everyone. I wouldn't put it into a separate .cpp file.

CygnusX1
  • 20,968
  • 5
  • 65
  • 109