D's structs are a good foundation to create a dynamic type. We'll create a tagged union to serve as a starting dynamic type. This is the technique used to implement the library jsvar
type that we used in a previous chapter. Here, we'll only support int
and string
.
We will execute the following steps to create a tagged dynamic type:
Write a struct with two members: a tag that holds the current type and a union that holds the possible types.
Make the data private and add checked getter and setter functions.
Add a constructor that takes the possible types. You may write it in terms of
opAssign
.Add type coercion if you want weak typing in the getter function; otherwise, throw an exception on type mismatches.
Implement other methods or operators you want.
The following is the code to create a tagged dynamic type:
struct Dynamic { enum Type { integer, string } private Type type; private union { int integer; string str; } this(T)(T t) { /...