Shameless autopromotion : type safe tagged union in D

Timon Gehr timon.gehr at gmx.ch
Fri May 10 12:52:22 PDT 2013


On 05/10/2013 02:32 PM, deadalnix wrote:
> 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.

I'd have implemented your TaggedUnion struct as follows. (I believe this 
is equivalent to your implementation.)

struct TaggedUnion(T...){
     private{
         union{ T members; }
         int tag;
         static int indexOf(S)(){
             foreach(i,t;T) static if(is(S==t)) return i;
             return -1;
         }
     }
     this(T)(T t) if(~indexOf!T){
         members[indexOf!T]=t;
         tag=indexOf!T;
     }
     auto ref apply(alias fun)(){
         switch(tag){
             foreach(i,_;T) case i: return fun(members[i]);
             default: assert(0);
         }
     }
}

But note that this is as unsafe as the original implementation. You will 
at least have to provide a postblit constructor and a destructor in 
order to keep the promise of safety.


More information about the Digitalmars-d-announce mailing list