Store struct tuple of alias and access members through it?

Alex sascha.orlov at gmail.com
Sat Apr 7 21:00:27 UTC 2018


On Saturday, 7 April 2018 at 13:31:01 UTC, Timoses wrote:

Simen was faster :)

In my solution I simply ignore such things as functions... But 
there is the cool delegate creation approach in Simen's solution 
for this. I can handle arrays instead. :)
And I got rid of tupelof acting on an instance.

Be aware, that bitfields create more fields then the delegates 
for the bitfield's members...

import std.stdio;
import std.bitmanip;
import std.traits;

void main()
{
     S s;
     Param!S example = new Param!S(s);

     writeln(example[0]);
     writeln(example[1]);
     writeln(example[2]);
     writeln(example[3]);
     writeln(example[4]);
     writeln(example[5]);
     writeln(example[6]);

     writeln([__traits(allMembers, S)]);

     writeln(example[15]);
     writeln(example[16]);
     writeln(example[17]);
     writeln(example[18]);
}

struct S
{
     uint s1;
     ushort s2;

     string s3;
     float s4;

     mixin(bitfields!(
         uint, "x",    2,
         int,  "y",    3,
         uint, "z",    2,
         bool, "flag", 1));

     size_t fun(){ return 42; }

     size_t delegate() dg;

     size_t[] arr;

     static void fun(){}
}

interface IParam{}

class Param(T) : IParam
{
     T m;
     this(T m)
     {
         this.m = m;
     }

     IParam opIndex(size_t i)
     {
         //static if(!isBasicType!T)
         static if(__traits(compiles, __traits(allMembers, T)))
         {
         	static foreach (j, t; __traits(allMembers, T))
         	{
         		if (i == j)
             	{
             		static if(__traits(compiles, new 
Param!(typeof(__traits(getMember, this.m, 
t)))(__traits(getMember, this.m, t))))
             		{
             			return new Param!(typeof(__traits(getMember, 
this.m, t)))(__traits(getMember, this.m, t));
             		}
            		}
         	}
         }
         return null;
     }
}


More information about the Digitalmars-d-learn mailing list