Part of the header file dlist.h is defined as:
#ifndef __DLIST_H__
#define __DLIST_H__
#include <iostream>
class emptyList {};
template <typename T>
class Dlist {
public:
bool isEmpty() const;
private:
struct node {
node *next;
node *prev;
T *o;
};
node *first; // The pointer to the first node (NULL if none)
node *last; // The pointer to the last node (NULL if none)
};
#include "dlist.cpp"
#endif
When I create a dlist.cpp file like this:
#include "dlist.h"
template <typename T>
bool Dlist<T>::isEmpty() const
{
return !first and !last;
}
I get the error message at line 4: redefinition of ‘bool Dlist::isEmpty() const’
If I remove the #include "dlist.h" I get the error at line 4: expected initializer before ‘<‘ token
Any help here? Is there something I’m doing wrong that’s not allowing me to just define my functions from the dlist.h file? Thank you.
You have to put the implementation of the class template’s member functions in the header file or in a file included by the header. The compiler needs access to this code in order to instantiate templates for any given type
T.In your case, the problem seems to be that you are including the header in the
.cppand vice versa. If you really want to keep declaration and implementation in separate files, I suggest changing the implementation’s suffix from.cppto something else, e.g..icpp. Some build systems might try to compile an object file out of anything with a.cppsuffix, and this would also result in error.#include "dlist.h"fromdlist.cpp.dlist.cppto something likedlist.icpp. Why? Because many build systems automatically compile any file ending in.cppinto an object file. And many programmers assume that a.cppfile will be compiled into an object file.dlist.icppindlist.h, as is currently done fordlis.cpp.