Static member variables in template class.

From: Graham Dumpleton (grahamd_at_dscpl.com.au)
Date: 02/29/04


Date: 29 Feb 2004 00:35:44 -0800

When you have a template class with a static member variable, ie.,

  template<typename T>
  class handle
  {
    public:
      static void* id() { return &id_; }
    private:
      static int id_;
  };

  template<typename T> int handle<T>::id_ = 0;

the compiler is supposed to ensure that for "each" typename T, there
is one and only one copy of the static "id_" variable.

In practice however, how widely is this implemented properly?

I know that in the past some compilers wouldn't event create the
space for the static "id_" variable and it was necessary to explicitly
define them in one spot. For example, it would have been necessary
to enumerate for all T of interest, something like:

  int unique<int>::id_ = 0;
  int unique<float>::id_ = 0;

Are things better now than they used to be? Are there any modern
compilers which still have strange caveats like this?

What I am hoping to be able to do is to use the address of that static
variable as a unique marker for a type. That is:

  template<typename T> void* id1() { return handle<T>::id(); }

  cout << "marker<int> = " << id1<int>() << endl;

There is also a simpler version one could write:

  template<typename T> void* id2() { static int i = 0; return &i; }

But how portable are such constructs across currently available and
not so current compilers? Can use of shared libraries/dlls complicate
the issue?

Thanks in advance.



Relevant Pages

  • Template member functions
    ... I'm having trouble with a template member function in a non template class. ... VisualAge compilers but Sun Workshop 6 doesn't like it. ... The sun compiler stumbles over the indicated line with the message "Badly ...
    (comp.lang.cpp)
  • Re: VC8 template base class member function visibility bug
    ... snippet from the standard even after reading it multiple times. ... access to two more compilers: GCC 4.1 doesn't compile it as well: ... "template class used without template parameters". ...
    (microsoft.public.vc.language)
  • Re: Access via use
    ... Andy wrote: ... > Another compiler dispute. ... either need to put a PUBLIC A_t in b_m, to remove the PRIVATE ... do the compilers vendors agree on what Fortran 95 is? ...
    (comp.lang.fortran)
  • Re: OO syntax
    ... expending time and space on techniques to prevent them. ... contains private: and public: keywords, ... and where few compilers will complain about such at ... With such a convention in place, ...
    (comp.lang.forth)
  • Re: OO syntax
    ... expending time and space on techniques to prevent them. ... contains private: and public: keywords, ... and where few compilers will complain about such ... to the internals variables/objects. ...
    (comp.lang.forth)