O'Reilly logo

D Cookbook by Adam D. Ruppe

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required