Where does one initialize a static template member?

A

Alan Johnson

Consider the following class template, which has the static member
'seed_'. This template is intended to be inherited by several other
classes using the curiously recurring template pattern, so that each
class gets its own copy of 'seed_'. I am not sure where to initialize
the static member, though. Putting it in the header as indicated below
works in g++ 4.1, but I would like to know if this is just luck or if
the standard requires it to work (for example, some clause stating that
static template members can be multiply defined if every definition is
identical, or such).

The FAQ and Google haven't helped me too much, nor have I had any luck
finding the relevant clauses in the standard. Thanks for any help.


// auto_identifier.h
#include <ctime>

template <typename T>
class auto_identifier
{
public:
auto_identifier()
: counter_(++seed_), timestamp_(std::time(0))
{}

unsigned counter() const
{
return counter_ ;
}

std::time_t timestamp() const
{
return timestamp_ ;
}

static void seed(unsigned s)
{
seed_ = s ;
}
private:
unsigned counter_ ;
std::time_t timestamp_ ;

static unsigned seed_ ;
} ;

template <typename T>
unsigned auto_identifier<T>::seed_ = 0 ;
 
A

Alf P. Steinbach

* Alan Johnson:
Consider the following class template, which has the static member
'seed_'. This template is intended to be inherited by several other
classes using the curiously recurring template pattern, so that each
class gets its own copy of 'seed_'. I am not sure where to initialize
the static member, though. Putting it in the header as indicated below
works in g++ 4.1, but I would like to know if this is just luck or if
the standard requires it to work (for example, some clause stating that
static template members can be multiply defined if every definition is
identical, or such).

Yep (it's required to work).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top