Shameless autopromotion : type safe tagged union in D

Dmitry Olshansky dmitry.olsh at gmail.com
Fri May 10 06:11:36 PDT 2013


10-May-2013 16:32, deadalnix пишет:
> http://www.deadalnix.me/2013/05/10/type-safe-tagged-union-in-d-programming-language/
>
>
> A trick that I used to use more and more, so I ended up creating a
> generic solution and wrote an article about it.

Neat but somewhat limited.

E.g. this is exactly the same switch madness we sought to avoid:

void process(T)(T data) {
     alias Type = typeof(data);

     static if(is(Type == A)) {
         // Code that handle the case where it is an A.
     } else static if(is(Type == B)) {
         // Code that handle the case where it is an B.
     } else {
         static assert(0, "You must handle type " ~ Type.stringof);
     }
}

t.apply!process();


I'd rather see another idiom supported too:

t.apply!(processA, processB)();

where e.g.
void proccessA(A value){ ... }

void processB(B value){ ... }

Anther thing is that will allow succinct notations like:

int squared = t.apply!(
	(A a) => a.x*a.x + a.y*a.y,
	(B b) => b.x*b.x + b.y*b.y + b.z*b.z
)();

I sure don't fancy putting static if into lambdas.
Another thing about it is it allows specifying safe catch all or default 
case.


-- 
Dmitry Olshansky


More information about the Digitalmars-d-announce mailing list