Topic: HELP with template


Author: gtj@goanna.cs.rmit.oz.au (Glenn T Jayaputera)
Date: 16 Mar 93 08:07:15 GMT
Raw View
Hi, I am wondering if somebody can give me some pointers re: my problem.
First, I ain't too sure if this problem is related to Borland C++
specifically or it is the nature of C++.

I am trying create a template class (the following is the simple example of
it). In the header file I declare:

#include <iostream.h>

template <class Type>
class tmpl  {
  Type a;
  public:
    tmpl(Type);
    ~tmpl()  {}
    show();
};

The definitions of constructor tmpl() and function member show() are located
in a separte file and are defined as follows:

#include "temp.h"

template <class Type>
tmpl<Type>::tmpl(Type x)  {
  a=x;
}

template <class Type>
tmpl<Type>::show(void)  {
  cout << a << endl;
}

The main module is defined is a separte file and is very simple, and as
follows:

#include <iostream.h>
#include "temp.h"

void main()  {
  tmpl<int> is(3);
  is.show();
}

I used the project file to inlcude the two .cpp files.  However,
when I try to generate the EXE file (ie link them), the linker complains with
message "undefined module tmpl()...." and "undefined module show()...".
If I put the definition of the tmpl() and show() together in one file with
the class declartion, everything works fine.

So I guess my question is, why can't I separate the definition and
declaration of a class template into two files?  Is this because the compiler
needs to generate the appropriate definition at compile time and hence needs
to see the functions' definition or I missed something that I should be aware
of.

Thanks for your comments
Glenn Jayaputera