Replace (ie: substitute) a type in varadic args

Sean Campbell via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 2 01:16:48 PDT 2016


On Tuesday, 2 August 2016 at 07:24:28 UTC, Saurabh Das wrote:
> How can I substitute the type of an argument received via a 
> varadic template?
>
> For example say I want to generalise this scenario:
>
> auto myConverterFunction1(bool arg1, bool arg2, ubyte arg3, int 
> arg4)
> {
>     return targetFunction(cast(ubyte)arg1, cast(ubyte)arg2, 
> arg3, arg4);
> }
>
> So I'll have something like:
>
> auto myConverterFunction2(Args...)(Args args)
> {
>     // Don't know how to do this part...
> }
>
> Basically I need to substitute bool for ubyte to interface with 
> the Java JNI.
>
> Thanks,
> Saurabh

Just of the top of my head, using ugly string mixins, this:
auto myConverterFunc(Args...)(Args args)
{
	string genCode()
	{
	    string code = "targetFunction(";
	    foreach (i, Arg; Args)
	    {
	        static if (is(Arg == bool))
	            code ~= format("cast(ubyte)args[%s]%s", i, i == 
Args.length ? "" : ",");
	        else
	            code ~= format("args[%s]%s", i, i == Args.length ? 
"" : ",");
	    }
	    code ~= ");";
	    return code;
	}
     mixin(genCode());
}

void targetFunction(ubyte i, ubyte j, uint k, int l)
{
	writefln("i : %s, j : %s, k : %s, l : %s",i,j,k,l);
}

void main()
{
	myConverterFunc(true,false,10,20);
}


More information about the Digitalmars-d-learn mailing list