www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - generating property from structs

reply Nicholas Wilson <iamthewilsonator hotmail.com> writes:
struct MyType
{
     void* ptr;
     static struct Info
     {
          (42) int foo;
     }

     // Should be generated by the mixin below
      property int foo()
     {
          int ret;
          getMyTypeInfo(ptr,42,int.sizeof,&ret);
          return ret;
     }
     mixin generateInfo!getMyTypeInfo;
}

extern(C) void getMyTypeInfo(void*,int, size_t,void*);

How do I write generateInfo info?

mixin template generateInfo(alias func)
{
     foreach(field; typeof(this).Info.tupleof)
     {
         //???
     }
}

I know I'll probably have to resort to string mixins, but how do 
I get the attribute so that I call
func(ptr,attibute, T.sizeof, &ret)? There will be a couple of 
values that dont have an attribute but they are all of known 
types and I want to handle them separately.

Thanks
Nic
Sep 30
parent user1234 <user1234 12.lo> writes:
On Saturday, 30 September 2017 at 08:20:44 UTC, Nicholas Wilson 
wrote:
 struct MyType
 {
     void* ptr;
     static struct Info
     {
          (42) int foo;
     }

     // Should be generated by the mixin below
      property int foo()
     {
          int ret;
          getMyTypeInfo(ptr,42,int.sizeof,&ret);
          return ret;
     }
     mixin generateInfo!getMyTypeInfo;
 }

 extern(C) void getMyTypeInfo(void*,int, size_t,void*);

 How do I write generateInfo info?

 mixin template generateInfo(alias func)
 {
     foreach(field; typeof(this).Info.tupleof)
     {
         //???
     }
 }

 I know I'll probably have to resort to string mixins, but how 
 do I get the attribute so that I call
 func(ptr,attibute, T.sizeof, &ret)? There will be a couple of 
 values that dont have an attribute but they are all of known 
 types and I want to handle them separately.

 Thanks
 Nic
You can use a struct that contains the value because apparently without you can only retrieve a specific value: --- struct ValueHolder{int value;} struct Foo { ValueHolder(42) int foo; int getTheValueDuringTheCall(string member)() { import std.traits; alias uda = getUDAs!(__traits(getMember, Foo, member), ValueHolder); static if (uda.length == 1) return uda[0].value; else return 0; } void test() { import std.stdio; writeln(getTheValueDuringTheCall!"foo"); } } void main() { Foo foo; foo.test(); } --- I mean that `getUDAs!(__traits(getMember, Foo, member), int);` wouldn't work.
Sep 30