#include "../include/myvector.h"
template<class T>
class MyVector;
template<class T>
MyVector<T>::MyVector() : v(NULL), m_size(0), max(0){}
template<class T>
void MyVector<T>::realloc(unsignedint value){
max = value;
v = (T *)::realloc(v, sizeof(T) * value);
}
template<class T>
unsignedint MyVector<T>::size(){
return m_size;
}
template<class T>
T &MyVector<T>::operator[](unsignedint i){
return v[i];
}
template<class T>
void MyVector<T>::push_back(T value){
if (m_size + 1 > max){
realloc(max + 100);
}
v[m_size++] = value;
}
template<class T>
void MyVector<T>::clear(){
if (v != NULL){
free(v);
v = NULL;
m_size = max = 0;
}
}
template<class T>
MyVector<T>::~MyVector(){
clear();
}
File "main.cpp":
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <cstdio>
#include "include/myvector.h"
int main()
{
MyVector<int> v;
for (int i = 0; i < 200; i++)
v.push_back(i);
for (size_t i = 0; i < v.size(); i++)
printf("%d\n", v[i]);
return 0;
}
If I put the contents of "src/myvector.cpp" into the end of "include/myvector.h", then it works just fine. Does someone know why???
obj\Debug\main.o: In function `main':
C:/.../Templates/main.cpp:6: undefined reference to `MyVector::MyVector()'
C:/.../Templates/main.cpp:8: undefined reference to `MyVector::push_back(int)'
C:/.../Templates/main.cpp:10: undefined reference to `MyVector::size()'
C:/.../Templates/main.cpp:11: undefined reference to `MyVector::operator[](unsignedint)'
C:/.../Templates/main.cpp:10: undefined reference to `MyVector::size()'
C:/.../Templates/main.cpp:13: undefined reference to `MyVector::~MyVector()'
C:/.../Templates/main.cpp:13: undefined reference to `MyVector::~MyVector()'
So, if needed, I'm using Code::Blocks on Windows with Mingw32...
When the compiler encounters this call to a template function, it uses the template to automatically generate a function replacing each appearance of myType by the type passed as the actual template parameter (int in this case) and then calls it. This process is automatically performed by the compiler and is invisible to the programmer.
Unless I've misunderstood something, that makes it rather hard to create an object file out of a file that has template definitions alone.