Metaprogramming with traits

Ram_B via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 15 15:05:55 PDT 2016


On Thursday, 15 September 2016 at 15:56:56 UTC, Gary Willoughby 
wrote:
> On Thursday, 15 September 2016 at 15:07:09 UTC, Ram_B wrote:
>> How i can get fields of derived classes in runtime? This not 
>> works
>
> What about something like this:
>
> import std.traits;
> import std.stdio;
>
> class A {
> 	int a,b;
> 	this(){}
> 	void fields(this T)(){
>         writeln(FieldNameTuple!(T));
>         foreach(Class; TransitiveBaseTypeTuple!(T)) {
>             writeln(FieldNameTuple!(Class));
>         }
> 	}
> }
>
> class B : A{
> 	int c;
> 	this(){}
> }
>
> class C : B{
> 	int d;
> 	this(){}
> }
> void main(){
> 	C c = new C();
> 	c.fields();
> }

This works, but i can't use (get|has)Member
class A{
	int a, b;
     Array!string fields(this T)(){
         Array!string list;
         foreach(field; FieldNameTuple!(T)){
             list.insertBack(field);
         }
         foreach(Class; TransitiveBaseTypeTuple!(T)){
             foreach(field; FieldNameTuple!(Class)){
                 list.insertBack(field);
             }
         }
         return list;
     }
	void t(this T)(){
		foreach(f; this.fields()){
			log(__traits(hasMember, T, f));		
		}
	}
}

class B : A{
	int c;
	this(){}
}

void main(){
	B b = new B();
	b.t();
}

test.d(33): Error: variable f cannot be read at compile time
test.d(33): Error: string expected as second argument of __traits 
hasMember instead of __error
test.d(46): Error: template instance test.A.t!(B) error 
instantiating


More information about the Digitalmars-d-learn mailing list