Thread overview
Constructing a tuple dynamically
Feb 03, 2015
Pena
Feb 03, 2015
Kagamin
Feb 04, 2015
thedeemon
February 03, 2015
I want to create a simple clone operator based on UDAs. First
step is to create a tuple of the fields with desired UDA value
and construct a clone method which uses that tuple.

import std.traits;

enum Cloneable;

struct Foo {
   @Cloneable int cloneableInt;
   @Cloneable string cloneableStr;
   float notCloneable;
}


I came up with this to iterate through fields and print out ones
with @Cloneable set:

foreach(member; __traits(allMembers, Foo)) {
   foreach(attr; __traits(getAttributes, mixin(member))) {
     static if(is(attr == Cloneable)) {
       pragma(msg, member);
     }
   }
}

How can I use this code or something similar to dynamically
construct a tuple containing types of fields marked as @Cloneable?
February 03, 2015
Try variadic templates with recursion.
For example see http://dpaste.dzfl.pl/f49a97e35974
February 04, 2015
On Tuesday, 3 February 2015 at 10:32:47 UTC, Pena wrote:
> How can I use this code or something similar to dynamically
> construct a tuple containing types of fields marked as @Cloneable?

import std.traits, std.typetuple;

template CloneableTypes(S) {
  template IsCloneable(string M) {
    enum IsCloneable = staticIndexOf!(Cloneable, __traits(getAttributes, __traits(getMember, S, M))) >= 0;
  }

  template FieldType(string M) {
    alias FieldType = typeof(__traits(getMember, S, M));
  }

  alias CloneableTypes = staticMap!(FieldType, Filter!(IsCloneable, __traits(allMembers, S)));
}

Then CloneableTypes!Foo is a TypeTuple (int, string).