Re: Template static member initialization
On Jul 26, 4:50 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
ALiX wrote:
My template class has a const static data member, which is used by the
constructor. It seems that the program does not produce the correct
result. Either it is the fault of the compiler (gcc 4.1) or I need to
learn more about initialization of static members... The code below
captures the problem and is as simple as I could make it:
#include <iostream>
#include <limits>
template<typename T> struct A {
const static unsigned NONE;
unsigned x;
A() { x = NONE; }
};
template<typename T> const unsigned A<T>::NONE =
numeric_limits<unsigned>::max();
A<double> a;
int main(void) {
cout << a.x << "\n";
cout << A<double>::NONE << "\n";
return 0;
}
The output of the program is:
0
4294967295
Mustn't NONE be initialized before a is constructed?
It's not *instantiated* unless it's "used". Perhaps referring to
it in the c-tor does not get it instantiated (and therefore does
not get it initialised), but I would consider it a compiler bug.
The standard says rather clearly (in =A73.6.2) that the order of
initialization of static variables in implicitly specialized
templates is unordered. In short, there is no guarantee that
the initialization will take place before the initialization of
a, in his code above.
In his code, the simplest solution would be to simply use static
initialization, i.e. initialize it with UINT_MAX. If the
initialization depended on the type, however, (e.g. was
std::numeric_limits<T>::max()), this is not an option. In such
cases, the best solution would probably be to use a static
member function.
Try initialising it right in the class:
template<typename T> struct A {
static unsigned const NONE
= std::numeric_limits<unsigned>::max();
unsigned x;
A() : x(NONE) {}
};
That's only legal if the initializer is a constant expression.
A constant expression cannot (at present, anyway) contain a
function call, even if the function is inline, and only returns
a constant value.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34