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 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
using namespace std;
template void StructStack::StructStack() {
//code
}
template void StructStack::~StructStack() {
//code
}
template AnyType StructStack::pop() {
//code
}
template void StructStack::push(AnyType value){
//code
}
template AnyType StructStack::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?
Answer
You can solve this by putting all the definitions (code you currently have in StructStack.cpp
) in StructStack.h
, and removing the former. The compiler needs to have access to the implementation code so it can instantiate the class template as needed.
No comments:
Post a Comment