Normalize void

Yuxuan Shui yshuiv7 at gmail.com
Tue Jul 10 09:50:45 UTC 2018


Suppose I want to create a type to contain either a return value 
or an error, I could probably do something like this:

     struct Result(T, E) {
         bool is_err;
         union {
             T result;
             E error;
         }
     }

This will probably work fine, unless I don't need an error for 
some of the use cases (i.e. I want it to behave more like a 
Nullable). I can't just pass 'void' to 'E', because I can't 
define variable with type void. So I will have to:

     struct Result(T, E) {
         bool is_err;
         union {
             T result;
             static if (!is(E == void))
                 E error;
         }
     }

I hope you can see what I mean here: 'void' is a special case I 
need to explicitly handle in templates. And special cases are bad.

What I want is for 'void' to behave like a normal type. This is 
not a crazy idea. 'void' can be considered as a unit type[0] in 
type theory. Basically, it is a type that can hold exactly 1 
value (so you don't need any storage space to store it). And it 
exists in many programming languages.

D actually already partially have 'void' as a unit type. For 
example:

void a() { return a(); } // returning void in a void function

Why don't we make it consistent across the whole language?

Here is how 'void' would behave if we made it a unit type:

     void a; // fine
     pragma(msg, a.sizeof); // 0
     void b = a; // fine
     writeln(a); // prints something intelligent about void

     struct A {
         void placeholder; // fine
     }
     pragma(msg, A.sizeof); // 1, same as empty struct

[0]: https://en.wikipedia.org/wiki/Unit_type


More information about the Digitalmars-d mailing list