Question about generation of template functions

Machine Code jckj33 at gmail.com
Wed Aug 28 20:56:25 UTC 2019


I was writing a recursive function that uses template, I thought 
it would generate the proper template function on the fly to 
match the type in the parameter but it seems to not so so and try 
to use the called function, resulting in the error:

> Error: function foo.serialize!(B).serialize(ref B output) is 
> not callable using argument types (A)
>        cannot pass argument output of type A to parameter ref B 
> output
> Error: template instance `foo.serialize!(A)` error instantiating

Code:

void main()
{
	A a = A();
	serialize(a);
}

struct Attr {
	string value;
	alias value this;
}


struct A {
	@(Attr("foo"))
	int n = 10;
	@(Attr("baa"))
	int k = 30;
	B b = new B();
}

class B {
	@(Attr("hello"))
	int pl = 10;
}

void serialize(T)(ref T output)
{
	import std.traits : hasUDA, getUDAs, isAggregateType;
	import std.meta : Alias;
	
	foreach(fieldName; __traits(derivedMembers, T))
	{
		alias field = Alias!(__traits(getMember, T, fieldName));
		static if(isAggregateType!(typeof(field)))
		{
			serialize!(typeof(field))(output);
		}
		static if(hasUDA!(field, Attr))
		{
			enum className = getUDAs!(field, Attr)[0];
			writefln("className = [%s]", className);
		}
	}
}


More information about the Digitalmars-d-learn mailing list