Reputation: 145
I am having trouble getting to grips with programming using templates in C++.
Consider the following files.
C.h
#ifndef _C_H
#define _C_H
template <class T>
class C {
public:
C();
virtual ~C();
}
#endif _C_H
C.cpp
#include "C.h"
template <class T>
C<T>::C() {
}
template <class T>
C<T>::~C() {
}
I try instantiate an instance of C in a file called main.cpp.
#include "C.h"
int main(int argc, char** argv) {
C<int> c;
}
I get the following error.
main.cpp undefined reference to `C<int>::C()'
I then run
g++ -o C.o C.pp
g++ -o main.o main.cpp
but get the error
main.cpp: undefined reference to `C<int>::C()'
main.cpp: undefined reference to `C<int>::~C()'
I am sure this probably an obvious mistake, but I am a real beginner at this so would appreciate any help.
Thanks!
Upvotes: 1
Views: 236
Reputation: 55009
When using templates, the source code is required to be available whenever the type is instantiated, because otherwise the compiler can't check that the template code will work for the given types. Dividing it into a .cpp and a .h file won't work, because the other .cpp files only know about the .h file.
You basically have to put everything in the .h file, or include an extra file with your implementation code.
Upvotes: 5