I'm trying to write an ArrayList class in c++, but run into the linking problem with templates as described in many places. I don't want to copy all my code into the header file. That would just be ugly. And the vector class probably didn't do that either right?
So how would I include my ArrayList implementation to any cpp file?
Here is my header File:
//ArrayList.h
#include <stdlib.h>
template <typename T> class ArrayList{
public:
ArrayList<T>(){
array = (T*)calloc(sizeof(T), 1);
length = 1;
elements = 0;
}
T get(int i);
void set(int i, T el);
void add(T el);
int expand(size_t n);
void remove(int i);
int size();
int reserved();
void fix_size();
private:
void copyAll(T arr1[], T arr2[], int len);
T *array;
int length, elements;
};
And here is part of my .cpp file:
#include <stdlib.h>
#include <stdio.h>
#include "ArrayList.h"
template <typename T> T ArrayList<T>::get(int i){
if (i > this->elements || i < 0) return (T)0;
return this->array[i];
}
template <typename T> int ArrayList<T>::size(){
return elements;
}
template <typename T> int ArrayList<T>::reserved(){
return length;
}
template <typename T> int ArrayList<T>::expand(size_t n){
// implementation
}
template <typename T> void ArrayList<T>::set(int i, T el){
// implementation
}
template <typename T> void ArrayList<T>::add(T el){
// implementation
}
template <typename T> void ArrayList<T>::remove(int i){
// implementation
}
template <typename T> void ArrayList<T>::copyAll(T arr1[], T arr2[], int len){
// implementation
}
template <typename T> void ArrayList<T>::fix_size(){
// implementation
}