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 structure with two views into the same data


Sometimes, it is useful to have a structure with multiple representations. This may be achieved with properties, but there is also a more direct way of doing it: using unions and anonymous structs. We'll create a Color structure with both RGBA and array representations.

How to do it…

To create a structure with two views into the same data, we need to execute the following steps:

  1. Write a struct to contain your type.

  2. Add a union without a name to hold the alternative representations.

  3. In the union, add the views. Be sure they match up in size and binary layout. For our Colorstruct, we'll want it to be represented by an array of ubytes with each byte also having a name.

  4. For the names, write a nameless struct with each named member.

  5. When using the structure, use the names directly.

To implement the preceding steps, we will have to execute the following code:

struct Color {
    union {
        ubyte[4] rgba;
        struct {
            ubyte r;
 ...