delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/05/14/14:32:59

From: "Les Noland" <LNoland AT instec-corp DOT com>
Newsgroups: comp.lang.c++,comp.os.msdos.djgpp,gnu.g++.help
Subject: Re: templates
Date: 14 May 1997 17:57:22 GMT
Organization: XNet - Chicagoland's Regional ISP (630) 983-6064
Lines: 78
Message-ID: <01bc6090$4c215020$2d97f3cd@lan>
References: <01bc5fc6$6d16b7e0$0b88099a AT dennis DOT worldonline DOT nl>
NNTP-Posting-Host: 205.243.151.45
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp


Dennis Janssen <nessnaj AT worldonline DOT nl> wrote in article
<01bc5fc6$6d16b7e0$0b88099a AT dennis DOT worldonline DOT nl>...
> Hi,
> 
> I'm new to C++ and now I'm trying to learn how to use templates.
> 
> I've written the following three files.
> 
> [CSTACK.H]
> #ifndef CSTACK_H
> #define CSTACK_H
> 
> template <class stackType>
> class cStack {
> public:
>   cStack();
>   int push(stackType element);
> };
> #endif CSTACK_H
> 
> [CSTACK.CC]
> #include <iostream.h>
> #include "cstack.h"
> 
> template<class stackType>
> cStack<stackType>::cStack()
> {
>   cout << "Constructed" << endl;
> };
> 
> template <class stackType>
> int cStack<stackType>::push(stackType element)
> {
>   cout << "Pushing..." << endl;
>   return 0;
> };
> 
> [TESTSTCK.CC]
> #include "cstack.h"
> 
> int main ()
> {
>   cStack<int> int_stack;
> 
>   int_stack.push(12);
> 
>   return 0;
> }
> 
> When I try to compile it using DJGPP 2.01 (based on gcc 2.7.0.1) I think
I
> get the following two errors:
> 
> undefined reference to cStack<int>::cStack(void)
> undefined reference to cStack<int>::push(int)
> 
> How do I fix this? I've read something in info about GCC neither
supporting
> the Borland model nor the C/C++ frontend (or something) but I don't
> understand how to fix it. 
> 
> 	Dennis!
> 
I believe your problem is that the compiler needs to know the definitions
for your templated constructor and push methods in order to instantiate
them when it compiles TESTSTCK.CC.  By defining them in a different
compilation unit, CSTACK.CC, their definition will only be known in that
compilation unit.

The easiest fix is to move them into the header file, CSTACK.H, so that
every user of the template also has the definitions of its methods.  I
don't know if there are advantages to structuring things in some other
manner, but that should do the job.

  - Les Noland

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019