G
Graham Dumpleton
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.
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.