Trait for "can be instantiated"?

H. S. Teoh hsteoh at quickfur.ath.cx
Tue May 10 16:05:15 UTC 2022


On Tue, May 10, 2022 at 03:26:28PM +0000, Ben Jones via Digitalmars-d-learn wrote:
[...]
> I'm writing a lexer and I'm using sumtype to store any of the token types.
> Some have values associated with them (like brackets and parens which are
> defined as `enum lparen = '('` or whatever) and some are just markers
> (keywords like 'if', which I'm trying to represent with just `enum if_token`
> ). The wrapper struct is there because I need a type for each one to use
> them as part of a sumtype and I only want to store the enum's value when it
> makes sense to.

A sum type in the case of token types is essentially the same thing as
an enum value, implementation-wise. Sum types are implemented
essentially as a discriminated union, which consists of a tag and a
variant payload.  The tag essentially behaves like an enum (and is in
fact often implemented as such), which determines the interpretation of
the payload.

Using wrapper structs, etc., for this is IMO total overkill. Just use an
enum for your token types.  Something like this would suffice:

	enum TokenType {
		lparen,
		rparen,
		if_token,
		...
		string_literal,
	}

	struct Token {
		TokenType type;
		union {
			string stringval;
			float floatval;
			... // etc.
		}
	}


T

-- 
Two wrongs don't make a right; but three rights do make a left...


More information about the Digitalmars-d-learn mailing list