switch to member

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 13 21:29:49 PST 2017


On Saturday, 14 January 2017 at 03:20:24 UTC, Ignacious wrote:
> When doing common functionality for a switch, is there any way 
> to optimize:
>
> switch(x)
> {
>     case X:
>          q.X = e;
>          break;
>     case Y:
>          q.Y = e;
>          break
>     etc...
> }
>
> e is basically a value that, depending on the what kind(x), we 
> assign it to a field in q. The name of the field and the case 
> label are identical(in fact, it wouldn't hurt to do it either 
> automatically(if x's enum name, if exists, matches a field, 
> auto assign) or create the field in the class q automatically 
> if the label matches a certain range or set).
>
> Basically the idea is to avoid duplicating a lot of code.
>
> I imagine one could write a string mixin that generates the 
> cases and assignments but I'm hoping for a more elegant 
> solution.

if `q` is the only data structure that  you are wanting to do 
this for
(or a 1:1 mapping for enum and type) then you can make
the enumeration values of x equal to the offsetof of q.
e.g. where typeof(q) == Q

enum XX
{
     X = Q.X.offsetof,
     Y = Q.Y.offsetof
     //ect.
}

and then

*(cast(void*)(this) + x) = e; //if inside struct/class

or
*(cast(void*)(q) + x) = e; // if outside

Unfortunately this loses you `@safe`ty, but as long as you trust
the value of x then it should be safe to `@trusted` that code.

If you are trying to avoid code duplication the enum declaration 
of X
could also be done with a string mixin.


More information about the Digitalmars-d-learn mailing list