Static members in templates in egcs-1.0.1

Joe Buck jbuck@synopsys.com
Wed Jan 14 04:17:00 GMT 1998


> I obtained egcs-1.0.1 and compiled it with the naive
> 
> ./configure
> make
> make install
> 
> on my i586-pc-linux-gnu system with glibc-2.0.5c-10, gcc-2.7.2.3-8
> and binutils-2.8.1.0.1-1 installed. It seems I can now use
> egcs as /usr/local/bin/gcc, which is cool.
> 
> But it seems that static members of templates still don't work:

Yes they do, if you use the correct syntax.

You aren't writing correct C++ code (though egcs should issue a diagnostic
for what you are writing: putting 'static T mycounter = 0' in a class
declaration is invalid C++).  You must both declare and define a static
member, and you can't initialize a static member at the point of
declaration.

I think the reason you aren't getting a message is because of a GNU
extension (permitting initialization of members within classes) that
has suffered from bit rot (no one ever tried this case).  It would be
best to just diagnose your code as an error, since it isn't going to work.

Here's how to write the code:

template <class T>
struct B
{
    static T mycounter;			// declare B<T>::mycounter
    void IncCounter() {mycounter++;}
};

// it's a common mistake for people not to write the following -- some
// older compilers will create the equivalent of 0-initialized static
// members, but it is an error to rely on this:

template <class T>
T B<T>::mycounter = 0;			// define B<T>::mycounter

int main()
{
     B<int> a;
     a.IncCounter();
     return 0;
}

original code:
>   template <class T>
>   struct B
>   {
>     static T mycounter = 0;           // with static - doesn't work with egcs
>     //T mycounter;                    // without static - works with egcs
>     void IncCounter() {mycounter++;}
>   };
>   
>   int
>   main()
>   {
>     B<int> a;
>     a.IncCounter();
>     return 0;
>   }



More information about the Gcc mailing list