[gnu.g++.bug] Static consts within classes?

steve@taumet.com (Stephen Clamage) (06/27/90)

In article <PCG.90Jun26213003@rupert.cs.aber.ac.uk> pcg@cs.aber.ac.uk (Piercarlo Grandi) writes:
>Ahhh. Too bad :-). Stroustrup loves enums, indeed they have been made
>local scope to a class definition as a special case because of that. Too
>bad, because consts make, IMNHO, enums redundant in C/C++...

Not at all redundant.  The declarations
	enum foo { zero, one, two };
and
	const int zero = 0;
	const int one = 1;
	const int two = 2;
have entirely different semantics, since the former defines a type,
and the identifiers zero, one, two are of type foo, not type int.
So if you have the declarations
	int myfunc(foo);
	int i;
and try to call it with
	myfunc(i);
it is an error, since the actual parameter is not automatically converted
to type foo.  Enums thus provide greater type safety where desired.


>Well, I am not even sure that it is legal to have const data members,
>whether static or not, and then where they can be initialized. Another
>of the many cases where C++ has been designed with little bother for
>orthogonality or consistency...

Again I beg to differ.  Const data members, static or not, are perfectly
legal, and initialized the same way as any other const object.  Look at
<iostream.h> for examples of their use (but not initialization).  I also
do not see to what inconsistency you refer.  Perhaps g++ does not follow
the C++ ARM, but please do not confuse g++ (or any specific C++ implementation)
with the definition of the C++ language.  Also note that g++ is not C++,
but is really another language with a lot in common with C++.

Example:

file mystruct.h:
	struct mystruct {
	    const int i;	// one copy in each object
	    static const int j;	// only one copy in whole program
	    static int k;	// only one copy in whole program

	    mystruct(int a) : i(a) { }	// only way to init i
	};

file mystruct.c:
	#include "mystruct.h"
	static const int mystruct::j = 1; // initialized here only
	static int mystruct::k = 2;	  // initialized here only

file myfile.c
	#include "mystruct.h"
	// now we can refer to static members of mystruct
	int z = mystruct::j + mystruct::k;

	mystruct x(3);	// instance of a mystruct
-- 

Steve Clamage, TauMetric Corp, steve@taumet.com