this is a piece of my header file that is a template and my implementtion file that is using it.I keep getting errors and dont know why,any help would be appreciated.

template<class T>
class List

{ public:


private:

T *list;
int size;
int numElements;

bool isValid(int location) const;
};

This is the implementation file

template<class T>
bool List<T>::isValid(int location) const
{
return (location>=0 && location<numElements);
}

Recommended Answers

All 3 Replies

You cannot (easily) separate the implementation and the declaration of a template. The compiler needs to have access to the implementation in order to instantiate the template for a given set of template-arguments. Read this.

Simply put all your implementations in the header file (either inside the declaration of the class template, or following it).

this is for school,they want them seperated for some reason.

To be able to separate the implementation from the declaration of a class template, you need to do a explicit instantiation of the class template for all the types you might need this class template for. This is very unusual when writing a class template, but possible.

If your school assignment specified to separate the implementation and the declaration, which is usual and preferred for non-template classes, then, are you sure it specified that you had to implement it as a class template? Know what your requirements are, because if it is to develop a class template and also to separate implementation|declaration, then it's a very unusual request.

Anyways, say you only need to use the class template for the type T = "int", then, in your cpp file, you can write the following statement after all the implementation of your functions:

template class List< int >;  //explicit instantiation.

If you need the class template for more types, you have to provide one such statement for every type you could possibly use your class template with. As you see, this is not a very practical solution.

The other alternative, if all you want is to have declarations in a header file and implementations in a cpp file, but you don't care that the cpp file be compiled on its own, then you can simple #include the cpp file at the end of your header file (within the include-guard).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.