Initializing static const class members

D

Daniel Switkin

Hi there,

I'm trying to do the following:

class tLimits {
static const int kIntMin = 0; // fine
static const float kFloatMin = 0.0f; // breaks
};

and I get this message:

error C2864: 'kFloatMin' : only const static integral
data members can be initialized inside a class or struct

We've been using this technique fine under gcc, both 2.9
and 3.3. Is there any reason VC++ .NET 2003 can't handle
a floating point static const initialized within the
header? Pushing the definition into the .cpp file will
cost a memory access which I don't want. Since I'm
passing classes like this to templates there's a big
rippling effect in this limitation. I'd really like to
see this fixed in a future release.

Thanks,
Daniel Switkin
 
T

Tomas Restrepo \(MVP\)

Hi Daniel,
I'm trying to do the following:

class tLimits {
static const int kIntMin = 0; // fine
static const float kFloatMin = 0.0f; // breaks
};

and I get this message:

error C2864: 'kFloatMin' : only const static integral
data members can be initialized inside a class or struct

We've been using this technique fine under gcc, both 2.9
and 3.3. Is there any reason VC++ .NET 2003 can't handle
a floating point static const initialized within the
header? Pushing the definition into the .cpp file will
cost a memory access which I don't want. Since I'm
passing classes like this to templates there's a big
rippling effect in this limitation. I'd really like to
see this fixed in a future release.


As Jeff pointed out, technically speaking, VC++ is perfectly conformant in
this regard, since the ISO spec defines constant initializers only for
static members of const integral or const enumeration types (see 9.4.2 sub 4
for the details).
 
D

Daniel Switkin

As Jeff pointed out, technically speaking, VC++ is
perfectly conformant in
this regard, since the ISO spec defines constant initializers only for
static members of const integral or const enumeration types (see 9.4.2 sub 4
for the details).

Thanks for the response, both of you. I suppose this is
one of those nice extensions I've gotten used to.

There are real optimizations to be had here, though. For
example, if I have a float constant of 1.0f in the
header, this lets gcc move 0x3f800000 directly rather
than doing a memory access, which could miss the cache.
I'm currently using these float constants for default
arguments to inline functions (i.e. the alpha channel of
a color class), among other uses.

So it may not be strictly required by the language, but
it would be nice to have (especially when using
templates - this is causing some integer code to slow
down as a result).

Cheers,
Daniel Switkin
 

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

Top