33

I'm having a curious issue, and I'm not quite sure what the issue is. I'm creating a class called LinkedArrayList that uses a typename template, as shown in the code below:

#pragma once

template <typename ItemType>

class LinkedArrayList 
{

private:

class Node {
    ItemType* items;
    Node* next;
    Node* prev;
    int capacity;
    int size;
};

Node* head;
Node* tail;
int size;

public:

void insert (int index, const ItemType& item);
ItemType remove (int index);
int find (const ItemType& item);
};

Now, this doesn't give any errors or problems. However, creating the functions in the .cpp file gives me the error "Argument list for class template 'LinkedArrayList' is missing." It also says that ItemType is undefined. Here is the code, very simple, in the .cpp:

#include "LinkedArrayList.h"

void LinkedArrayList::insert (int index, const ItemType& item)
{}

ItemType LinkedArrayList::remove (int index)
{return ItemType();}

int find (const ItemType& item)
{return -1;}

It looks like it has something to do with the template, because if I comment it out and change the ItemTypes in the functions to ints, it doesn't give any errors. Also, if I just do all the code in the .h instead of having a separate .cpp, it works just fine as well.

Any help on the source of the problem would be greatly appreciated.

Thanks.

1 Answer 1

41

First of all, this is how you should provide a definition for member functions of a class template:

#include "LinkedArrayList.h"

template<typename ItemType>
void LinkedArrayList<ItemType>::insert (int index, const ItemType& item)
{}

template<typename ItemType>
ItemType LinkedArrayList<ItemType>::remove (int index)
{return ItemType();}

template<typename ItemType>
int LinkedArrayList<ItemType>::find (const ItemType& item)
{return -1;}

Secondly, those definitions cannot be put in a .cpp file, because the compiler won't be able to instantiated them implicitly from their point of invocation. See, for instance, this Q&A on StackOverflow.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.