Using Templates
Template files
As usual, we put the class template in the .h file and the implementation in the .cpp file.
Same for function templates.
But if the user only includes the .h file, and the .h file contains just the
member function prototypes, how does the compiler generate the code if the
function templates are in the .cpp file?
The answer is compiler specific.
For the g++ compiler, the source code and the prototypes must be in the same
file. To accomplish this (and yet have separate .h and .cpp files), we
#include the .cpp file at the bottom of the .h file.
This ONLY applies to templates
SmartArray.h
#ifndef SMARTARRAY_H
#define SMARTARRAY_H
template
class SmartArray
{
public:
SmartArray ( int size = 100 );
// other members
private:
int m_size;
T *m_theData;
};
#include "SmartArray.cpp"
#endif
Compiling Templates
Function and class templates are just that -- templates (i.e., frameworks) that tell the
compiler how to generate code. The compiler can't generate any meaningful code until it
knows what type to use in place of the template type parameter.
So compiling SmartArray.cpp will never create a meaningful SmartArray.o, so we don't
include rules for making SmartArray.o in our makefile. The code will be generated when
the compiler encounters your code that uses the class
template (ie. SmartArray<int> array2;)
We may want to compile SmartArray.cpp to check for syntax errors (using the -c switch),
but we have to be careful.
Since SmartArray.cpp #includes SmartArray.h and SmartArray.h #includes SmartArray.cpp,
we're going to include the code for SmartArray.cpp twice, resulting in compiler errors.
The solution is to guard SmartArray.cpp as well as SmartArray.h. Note that this
applies only to templates.
#ifndef SMARTARRAY_CPP
#define SMARTARRAY_CPP
#include "SmartArray.H"
// SmartArray.cpp code here
#endif
Now it's possible to do everything you want. You can compile SmartArray.cpp
(using the -c switch) to check for syntax errors and you can #include
SmartArray.h in your files that need it.