Re: Q: member `XXX' with constructor not allowed in union.
Posted in 1999
Topics: General Discussion
Bjorn Eriksson wrote: > Converting the following C-code to C++ posed some problems > for me. I've read ARM section 9.4 but doesn't understand it... > Any suggestions? > typedef struct unused_tag_VAR_T { > string name; > VAR_TYPE_T type; > int size; //or parameter-count or ... > union unused_tag_v { > struct unused_tag_local_fp { > vector<operator_stream> opstream; > int starting_line_nr; // Starting linenumber or > // om -1 for builtins. > vector<line_entry> lines; > } local_fp; > struct { > void *valp; > void far *ackp; > } n; > void (*funcp)(void); > } v; > } VAR_T; > I realize that it is the members 'vector<operator_stream> opstream' > and 'vector<line_entry> lines' in the structure local_fp that are in > violation with the standard but I don't understand how to write around > this limitation. > //Bj'rn The basic suggestion in C++ is that you do not need unions, they are too troublesome. Usually rethinking the design offers more advantages. If that is too much work, how about: struct local_fp { vector<operator_stream> opstream; int starting_line_nr; // Starting linenumber or // om -1 for builtins. vector<line_entry> lines; }; struct n // Come up with a better name { void *valp; // Really void*, or ? void /*far*/ *ackp; // far is not C++, nor C }; struct VAR_T { // Don't need typedef in C++ string name; int size; //or parameter-count or ... private: // Don't give anybody access to this union VAR_TYPE_T type; union { // Don't need a tag local_fp* Local_fp; n* N; void (*funcp)(void); } v; public: local_fp& Get_local_fp() { if (type!=ENUM_LOCAL_FP) throw not_in_union; return *(v.Local_fp); } void Set_local_fp(local_fp& newlfp) { if (type!=ENUM_EMPTY) throw union_not_empty; v.Local_fp = new local_fp; *(v.Local_fp) = newlfp; type=ENUM_LOCAL_FP; } /* Other Gets & Sets */ } In this way, you have a small design improvement, too. Nobody can get "forget" to check the type. HTH, Michiel Salters [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ] [ about comp.lang.c++.moderated. First time posters: do this! ]