#include "stdafx.h"
template <class ArrayType>
int getarraysize(ArrayType a[]) {
int c = 0;
while ((a[c] != NULL) && (a[c] != '\0')) {
c++;
}
return c;
}
template <class ArrayType>
int copyarray(ArrayType a[], int ns) {
int c = 0; // index counter
char* ca = newchar[ns]; // new array
int s = getarraysize(a);
while (c <= s) {
ca[c] = a[c];
c++;
}
delete[] a;
a = ca;
return ns;
}
Here is the main CPP file where I was trying to include the header file in:
// InputTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h" // The header file I mentioned just now is included in stdafx.h
usingnamespace std;
void getdat(char* a) {
char d = NULL;
int c = 0;
int s = 20;
cin.get(a, s);
if (a[getarraysize(a)]) {
while ((d != NULL) && (d != '\0')) {
cin.get(d);
s = copyarray(a, s + 10);
cin.get(d);
c++;
a[c] = d;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Insert data: ";
char* buf = newchar[20];
getdat(buf);
int c = 0;
while (buf[c] != NULL) {
cout << buf[c];
c++;
}
char w;
cin >> w;
return 0;
}
Can anyone tell me why these linking errors happen?
Yes. Because you are trying to use the template in a different compilation unit (A different .cpp from which it was defined) it will not link. If you only used the template in the templates .cpp then your implementation is fine. Since you want to use it in main, you will need to put the template implementation from your .cpp file in the templates header file.
Also, the reason I defined ArrayType twice in both the header and CPP file is the fact that one of the functions that was not with the template would complain of ArrayType being non-existent.
#include "stdafx.h"
template <class ArrayType> // Definition
int getarraysize(ArrayType a[]) {
int c = 0;
while ((a[c] != NULL) && (a[c] != '\0')) {
c++;
}
return c;
}
template <class ArrayType>
int copyarray(ArrayType a[], int ns) {
int c = 0; // index counter
char* ca = newchar[ns]; // new array
int s = getarraysize(a);
while (c <= s) {
ca[c] = a[c];
c++;
}
delete[] a;
a = ca;
return ns;
}
#include "stdafx.h"
template <class ArrayType> // Declaration
int getarraysize(ArrayType a[]);
template <class ArrayType>
int copyarray(ArrayType a[], int ns);
template <class ArrayType> // Definition
int getarraysize(ArrayType a[]) {
int c = 0;
while ((a[c] != NULL) && (a[c] != '\0')) {
c++;
}
return c;
}
template <class ArrayType>
int copyarray(ArrayType a[], int ns) {
int c = 0; // index counter
char* ca = newchar[ns]; // new array
int s = getarraysize(a);
while (c <= s) {
ca[c] = a[c];
c++;
}
delete[] a;
a = ca;
return ns;
}