1

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?

Community
  • 1
  • 1
Marco7757
  • 735
  • 9
  • 16

4 Answers4

3

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

You just need to put the definitions of your functions inside the header file. Everything you wrote inside StructStack.cpp should go in StructStack.h after the class definition.

alestanis
  • 21,519
  • 4
  • 48
  • 67
1

Templated code needs to be seen by every file file that needs to use it.

It doesn't get compiled until it gets specialized or used.

Basically if you want to use it in different files, you'll have to put it in the header file, and then include it. When you actually use the templates with a certain type, the code will be generated in the context it is used in.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
0

C++ Templates code should always be put in a header file so the implementation will be visible in every translation unit where you would like to instantiate the template. If you like you can separate the code to *.h and *.cpp files but you should still #include *.cpp file at the end of *.h file.

Mateusz Pusz
  • 1,363
  • 1
  • 9
  • 16