Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a tagged dynamic type


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.

How to do it…

We will execute the following steps to create a tagged dynamic type:

  1. Write a struct with two members: a tag that holds the current type and a union that holds the possible types.

  2. Make the data private and add checked getter and setter functions.

  3. Add a constructor that takes the possible types. You may write it in terms of opAssign.

  4. Add type coercion if you want weak typing in the getter function; otherwise, throw an exception on type mismatches.

  5. 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) { /...