Re: About static member variable
* Juha Nieminen:
Alf P. Steinbach wrote:
Constants are not problematic, just use 'const':
const int x = 42;
He was talking about *member* variable (well, a static "member"
variable would technically not be a member variable but a class
variable, but I assume that with "member variable" he meant "class
variable", ie. a static variable inside the scope of a class).
You can't write that for member variables (well, at least not until
the next C++ standard). You can, however, write this:
static const int x = 42;
For integral type, yes.
Sorry, I didn't see that about member variables.
However, the two solutions I mentioned, "technical solutions to
non-const static variable in headers include using local statics
(wrapping in functions) and templatizing", work also for member constant
variables, including non-integral ones.
struct Foo
{
static double x() { return 3.15; }
};
// Foo::x()
template< typename Dummy > struct XValue{ static double const x; }
template< typename Dummy > double const XValue<Dummy>::x = 3.15;
struct Bar: XValue<void> {};
// Bar::x
I'm wondering though: What does the standard say about such static
const variables? Do they need an actual instance or not?
If such a variable is used in a way that requires it has an address. With
static const int x = 42;
as a member variable it becomes a declaration instead of definition
(very confusing), and then a definition outside the class definition is
required, which looks like a declaration:
int const SomeClass::x;
and which is problematic in a header file.
And which is also generally problematic. Different compilers differ in
how strictly they interpret the standard in this respect. A compiler
(or in practical terms linker) may choke on code that follows the standard.
So, best avoided.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?