tags:

views:

88

answers:

2

Hi,

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!

A: 

You left out the final }; in the first C.h class.

wheaties
He's also missed the closing } on the implementation of his destructor.
No one in particular
Sorry! These have now been added.
bandini
+6  A: 

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.

Michael Madsen
Thanks very much. A misunderstanding stemming from trying to learn C++ from a background in java.
bandini
+1: There are other ways, but for a beginner this is plenty sufficient.
John Dibling