I'm having a problem getting templates to work in a program. I haven't used them for a while, so maybe I'm confused somehow as to how to use them correctly. I looked it up and it seems that I have the right syntax though. I do not get a compile error. I get a linker error. I'm using Deviant C++ by the way, but I don't think this is an issue specific to the compiler. Here's the code that's giving me problems...
In a file called arrays.cpp, I have this:
The arrays.h header has this:
Now the code that gives me problems looks like this:
The linker gives me an error saying:
[Linker error] undefined reference to `GenericArray2DStruct<unsigned char>* allocate2DArray<unsigned char>(unsigned int, unsigned int)'
Can anyone help me out? Why is this happening and how do I fix it? Thanks in advance!
In a file called arrays.cpp, I have this:
Code:
#include "arrays.h"
template <typename T> GenericArray2DStruct<T>* allocate2DArray (unsigned int xs, unsigned int ys) {
int i;
//allocate the struct itself
GenericArray2DStruct <T> *prod = (GenericArray2DStruct <T>*) malloc(sizeof (GenericArray2DStruct <T>));
if (prod == NULL) {
printf ("Insufficient memory to execute!"); }
//allocate the array of pointers to arrays
prod->data =(T**) malloc(sizeof(T*)*ys);
if (prod->data == NULL) {
printf ("Insufficient memory to execute!"); }
//allocate each of the arrays
for (i=0;i<ys;i++) {
prod->data [i] = (T*) malloc(sizeof(T)*xs);
if (prod->data [i] == NULL) {
printf ("Insufficient memory to execute!"); }}
prod->xSize = xs;
prod->ySize = ys;
return prod; }
The arrays.h header has this:
Code:
template <class T>
typedef struct GenericArray2DStruct{
int xSize;
int ySize;
T **data; };
template <class T>
GenericArray2DStruct<T>* allocate2DArray (unsigned int xs, unsigned int ys);
Now the code that gives me problems looks like this:
Code:
#include "arrays.h"
using namespace std;
image1Array = allocate2DArray <unsigned char> (100, 100);
The linker gives me an error saying:
[Linker error] undefined reference to `GenericArray2DStruct<unsigned char>* allocate2DArray<unsigned char>(unsigned int, unsigned int)'
Can anyone help me out? Why is this happening and how do I fix it? Thanks in advance!