www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/12/27/17:51:29

Date: Sat, 28 Dec 1996 11:30:06 +0000
From: Bill Currie <billc AT blackmagic DOT tait DOT co DOT nz>
Subject: Re: C++ inline members in templates are not expanded
To: "A.V. Kondratiev" <akondra AT mmf DOT univ DOT simbirsk DOT su>
Cc: djgpp AT delorie DOT com
Reply-to: billc AT blackmagic DOT tait DOT co DOT nz
Message-id: <32C504BE.205E@blackmagic.tait.co.nz>
Organization: Tait Electronics NZ
MIME-version: 1.0
References: <AATmccX1pst AT mmf DOT univ DOT simbirsk DOT su>

A.V. Kondratiev wrote:
> 
> It is something strange with inline members in templates.
> In the following sample
> 
> template <class T> class Array {
> public:
>     Array(unsigned sz = 0 ): data(0), lim(sz) {
>       if (lim) data = new T[sz];
>     }
> 
>     ~Array() {
>        if (data) delete [] data;
>      }
> 
>     inline T  & operator [] ( unsigned index ) const {
>       return data[index];
>     }
> 
> protected:
>     T  * data;
>     unsigned lim;
> };
> 
> int main() {
>   Array<int> a(10);
>   int i;
>   i=a[5];      //!!!!!!!!!!!!!!!
>   return 0;
> }
> 
> Array<int>::operator[] is not expanded inline compiling by gcc 2.7.2.1
> gcc -S -O -g0 name.cc. I tried different options but it seems that compiler
> does not pay attention to inline directive in templates . Particularly
> Array<int>::operator[] must be inline without any 'inline' directives
> because it's body is in the class declaration and such simple members are
> really needed to be inline! HOW? Please, send your answers
> to my e-mail. Thank you.
> 
> Aleksey V. Kondratyev, Simbirsk, Russia
> akondra AT mmf DOT univ DOT simbirsk DOT su

I had some problems with this myself.  The solution is really very
simple (and in the docs).  You declare an 'instance' of the template. ie
put the following line somewere before the first use of your template
(for the int type of course).

template class Array<int>;


If you use the '#pragma interface/implementation' commands (and some
template related command line options I think) gcc will do the right
thing and only make one copy of the inlines in your whole application.

Bill
-- 
Leave others their otherness.

- Raw text -


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