C++98 template class static member initialization?

235 views Asked by At

In a large C++ code base, originally written @ 2001, a Singleton class is used heavily, and is defined like:

   template <class T> 
   struct Singleton 
   { T *Instance() { return _instance; }
   ... 
     static T *_instance;
   }; 
   #define INIT_SINGLETON(T) \
    T * Singleton <T>::_instance = ((T*)0UL)

Now, with GCC 4.7.7, which I MUST use, with the default c++98 standard, and a use of INIT_SINGLETON(structX) in a test file, I get:

   $ g++ -std=c++98 -c /tmp/ts.cpp 
   /tmp/ts.cpp:11: error: too few template-parameter-lists

The code last compiled OK with GCC 3.4.3 on Linux RHEL3 - I am trying to port it to RHEL6 (GCC 4.4.4 / 4.7.7).

It's been a while since I used C++98 code, though I've used C++ since @ 1994 , I can't seem to get my head around this one today.

Could anyone please shed some light on why this error occurs and how to avoid it ?

In response to S.M.'s & NathanOliver's request, this is /tmp/ts.cpp:

    template <class T> 
    struct Singleton 
    { T * Instance() { return _instance; } 
      T * _instance; 
    }; 

    struct ab_s { int a, b; }; 

    typedef Singleton<ab_s> S_ab_s_t; 

    ab_s* f(S_ab_s_t sa)
    { return sa.Instance(); 
    }

    ab_s * Singleton<ab_s> :: _instance = NULL; 

GCC 4.7.7 gives error:

    $ g++ -std=c++98 -Isonim/MRFP/inc -c /tmp/ts.cpp  
    /tmp/ts.cpp:15: error: too few template-parameter-lists
1

There are 1 answers

3
273K On

Template specialization requires template<>.

#define INIT_SINGLETON(T) \
    template<> \
    T * Singleton<T>::_instance = ((T*)0UL)

The compiling example

template <class T> 
struct Singleton 
{
  T *Instance() { return _instance; }
  static T *_instance;
}; 

#define INIT_SINGLETON(T) \
  template<> \
  T * Singleton<T>::_instance = ((T*)0UL)

struct structX{};

INIT_SINGLETON(structX);

To the updated question:

template<>
ab_s * Singleton<ab_s> :: _instance = NULL;