Re: Dynamically setting struct values from hash map

2016-05-12 Thread Andrew Chapman via Digitalmars-d-learn

On Thursday, 12 May 2016 at 21:01:06 UTC, Adam D. Ruppe wrote:


foreach(member; __traits(allMembers, YourStruct))
  if(member in yourhash)
   __traits(getMember, your_object, member) = 
to!right_type(yourhash[member]);



basically, it is a bit more complex to filter out inappropriate 
fields and such, but that's the idea.


Check out the sample chapter of my book 
https://www.packtpub.com/application-development/d-cookbook to 
see more, you can get the reflection chapter free on that site.


That's wonderful Adam, thank you!  I actually had your book 
previously bookmarked - I should probably buy it :-)


Re: Dynamically setting struct values from hash map

2016-05-12 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 12 May 2016 at 20:52:46 UTC, Andrew Chapman wrote:
I have seen the "allMembers" method from the traits module that 
can give me the names of the struct fields, but I am unsure if 
it's even possible to set the struct values using 
variable/dynamic names.



Yes.

You can't loop over the hash and set values on the struct, since 
looping a hash is a run time operation, but you can loop over 
struct members.


So, the trick is to loop over the struct members (a compile-time 
operation) and set them (converting type with `std.conv.to` if 
necessary) if the value is in the hash.


foreach(member; __traits(allMembers, YourStruct))
  if(member in yourhash)
   __traits(getMember, your_object, member) = 
to!right_type(yourhash[member]);



basically, it is a bit more complex to filter out inappropriate 
fields and such, but that's the idea.


Check out the sample chapter of my book 
https://www.packtpub.com/application-development/d-cookbook to 
see more, you can get the reflection chapter free on that site.