Possible Duplicate:
Why can templates only be implemented in the header file?
Why should the implementation and the declaration of a template class be in the same header file?
I’m working on a project where I need my “stack” to save data. But I don’t want to code a different version for every single filetype (and I don’t want to use vectors).
So I’m trying to use a template class, and this is my code:
StructStack.h
#ifndef STRUCTSTACK_H_
#define STRUCTSTACK_H_
template <class AnyType> class StructStack {
StructStack();
~StructStack();
struct Element {
Element *pointer;
AnyType value;
};
Element *pointerToLastElement;
int stackSize;
int pop();
void push(int value);
int size();
};
#endif
StructStack.cpp
#include "stdafx.h"
#include "StructStack.h"
#include <iostream>
using namespace std;
template <class AnyType> void StructStack<AnyType>::StructStack() {
//code
}
template <class AnyType> void StructStack<AnyType>::~StructStack() {
//code
}
template <class AnyType> AnyType StructStack<AnyType>::pop() {
//code
}
template <class AnyType> void StructStack<AnyType>::push(AnyType value){
//code
}
template <class AnyType> AnyType StructStack<AnyType>::size() {
//code
}
If I try to compile these two files, I’m getting a bunch of compiling errors. I read online that it is kind of hard to create a template class in a multiple-file project.
So how can this be done?
You can solve this by putting all the definitions (code you currently have in
StructStack.cpp) inStructStack.h, and removing the former. The compiler needs to have access to the implementation code so it can instantiate the class template as needed.