Need Advice: Union or Variant?

H. S. Teoh hsteoh at qfbox.info
Thu Nov 17 22:49:37 UTC 2022


On Thu, Nov 17, 2022 at 10:16:04PM +0000, jwatson-CO-edu via Digitalmars-d-learn wrote:
> On Thursday, 17 November 2022 at 21:05:43 UTC, H. S. Teoh wrote:
[...]
> > 	struct Atom {
> > 		F_Type kind;
> > 		union {		// anonymous union
> > 			Atom*   car; // ----------------- Left  `Atom` Pointer
> > 			Atom*   cdr; // ----------------- Right `Atom` Pointer
> > 			double  num; // ----------------- Number value
> > 			string  str; // ----------------- String value, D-string underlies
> > 			bool    bul; // ----------------- Boolean value
> > 			F_Error err = F_Error.NOVALUE; // Error code
> > 		}
> > 	}
[...]
> Thank you!  This seems nice except there are a few fields that need to
> coexist.
> I need {`car`, `cdr`} -or- {`num`} -or- {`str`} -or- {`bul`}.
> `err` will be outside the union as well because I have decided that
> any type can have an error code attached.  As in an error number
> (other than NaN) can be returned instead of reserving certain numbers
> to represent errors.  Imagine if there was NaN for every datatype.
[...]

Just create a nested anonymous struct, like this:

 	struct Atom {
 		F_Type kind;
 		union {		// anonymous union
			struct {
				Atom*   car; // ----------------- Left  `Atom` Pointer
				Atom*   cdr; // ----------------- Right `Atom` Pointer
			}
			struct {
				double  num; // ----------------- Number value
				string  str; // ----------------- String value, D-string underlies
			}
 			bool    bul; // ----------------- Boolean value
 		}
 		F_Error err = F_Error.NOVALUE; // Error code
 	}


T

-- 
Meat: euphemism for dead animal. -- Flora


More information about the Digitalmars-d-learn mailing list