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

Storing a range as a data member


Storing a range instance in a non-template class or struct can be difficult because the type isn't always obvious and is sometimes completely unavailable. Ranges are typically for temporary use, and thus they don't need to be stored for long and are usually eligible for auto type deduction, but if you do need to store it, there are two options.

How to do it…

We can store a range as a data member by executing the following steps:

  1. The first option is to use one of the object-oriented wrappers as follows:

    import std.range;
    InputRange!int rangeObj;
    rangeObj = inputRangeObject(your_range);

    Remember, there is a performance penalty for this method, but it does have the advantage of being reassignable by different types of ranges as needed.

  2. Alternatively, we can use the typeof operator to get the range type out of the function, as shown in the following code:

    typeof(function_that_returns_a_range) rangeObj;

The code is as follows:

import std.algorithm;
typeof(filter!((a) ...