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 ranged integer


We saw in the previous chapter how we can make a not null type. We can use similar techniques to make an integer that is forced to stay in a particular range.

How to do it…

To create a ranged integer, execute the following steps:

  1. Create a struct with an integer member.

  2. Disable the default constructor.

  3. Overload the arithmetic operators by using string mixins to automate most of the code generation process.

  4. Insert range checks into the overloaded functions.

  5. Use a getter property with alias this to allow implicit conversion to int.

Execute the following code:

struct RangedInt(int min, int max) {
    private int _payload;
    @disable this();

    this(int value) {
        _payload = value;
        check();
    }

    RangedInt check() {
        assert(_payload >= min);
        assert(_payload < max);
        return this;
    }

    RangedInt opUnary(string op)() {
        RangedInt tmp = _payload;
        mixin("tmp= " ~ op ~ "_payload;");
        return tmp.check();...