Re: [Dev-C++] Template implementation in cpp file linking error
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Siva C. <siv...@ya...> - 2005-03-28 03:17:34
|
Hello all,
It would be great if someone can throw light on this.
I use templates quite a lot but declare and define in
the same header file.
As I understand it:
-------------------
When we use template classes, the compiler generates
the code, at compile time, for the right 'type' of our
choice using our definitions for the template class.
For example, lets look at an Array class.
template < class T >
class Array
{
public:
Array(void);
// Creates an array of size n and initialises
// the values to initVal at the time of
// construction.
Array(int n, T initVal);
// Creates an array of size n and initialises
// the values to initVal. This should ideally
// ideally be used if the object was made
// using the default constructor!
Create(int n, T initVal);
private:
...
...
};
I put the definitions for the member functions also in
the same header file. Now, if we want to create an
integer array, the compiler would generate the code
using our definitions and declarations as:
class Array
{
public:
Array(void);
// Creates an array of size n and initialises
// the values to initVal at the time of
// construction.
Array(int n, int initVal);
// Creates an array of size n and initialises
// the values to initVal. This should ideally
// ideally be used if the object was made
// using the default constructor!
Create(int n, int initVal);
private:
...
...
};
Also, not all member functions will be synthesized by
the compiler. Only those called in our program are
synthesized.
Using this interpretation of mine for the templates,
we can clearly see why your code throws linker errors.
The compiler has not generated the code required as it
does'nt know where the code (or the definition of the
class) is!
The above explanation I have given is what I could
reverse engineer from my experience and the hell a lot
of error messages I get while making my way through
templates. Do not take the explanation as the right
one. Any pointers to mistakes and misconceptions of
mine will be greatly appreciated.
Thanks in advance,
Siva Chandra.
--- Behcet Emre Tezel <emr...@gm...> wrote:
> Hi,
>
> Is the following a known problem?
>
> I define a template class in a header file. Then I
> implement the
> methods in a cpp file. The code compiles fine, but
> it throws a linking
> error for the methods that are implemented in the
> cpp file.
>
> Any help greatly appreciated.
>
> Thanks,
> Emre
__________________________________
Do you Yahoo!?
Yahoo! Small Business - Try our new resources site!
http://smallbusiness.yahoo.com/resources/
|