Associative array to Struct at compile time
John Colvin via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jul 25 08:48:53 PDT 2014
On Friday, 25 July 2014 at 15:25:43 UTC, BlackEdder wrote:
> Is it possible to automatically convert an associative array to
> a
> struct?
>
> Basically I want to do the following (for any struct).
>
> struct A {
> double x = 1;
> }
>
> double[string] aa = ["x":1];
>
> auto a = toStruct!A( aa );
>
> I've been trying to do this at compile time, but can't work out
> how setMembers and or loop over the associative array at compile
> time.
>
> Is this possible at all?
one possible way:
enum aa = ["x": 1];
import std.traits;
struct AAtoStruct(alias aa)
if(isAssociativeArray!(typeof(aa)) &&
isSomeString!(KeyType!(typeof(aa))))
{
alias T = ValueType!(typeof(aa));
import std.range, std.algorithm, std.array;
mixin(zip(aa.keys, aa.values)
.map!`"T " ~ a[0] ~ " = " ~ a[1].to!string ~ ";\n"`
.joiner.array);
}
alias S = AAtoStruct!aa;
More information about the Digitalmars-d-learn
mailing list