Heterogeneous Variadic Arguments with Other Arguments

harakim harakim at gmail.com
Sun Jul 14 03:51:14 UTC 2019


I wanted to do this:
package int serialize(byte[] destination, int offset, T...)(T 
values)
{	
	static foreach (i, value; values)
	{
		*cast(T[i] *)(destination.ptr + offset) = value;
		offset += typeid(T[i]).tsize();
	}
	
	return offset;
}

But I got this error:
main.d(8): Error: template main.serialize cannot deduce function 
from argument types !()(byte[], int, byte, int), candidates are:
main.d(20):        main.serialize(byte[] destination, int offset, 
T...)(T values)

Eventually, I assumed that you couldn't do heterogeneous 
arguments with other arguments first.

I was able to do this and it works:
package int serialize(T...)(T values)
{
	static assert(values.length >= 2);

	auto ptr = (cast(byte[])values[0]).ptr;
	
	int offset = cast(int)values[1];

	static foreach (i, value; values)
	{
		static if (i > 1)
		{
			*cast(T[i] *)(ptr + offset) = value;
			offset += typeid(T[i]).tsize();
		}
	}
	
	return offset;
}

That is obviously a lot uglier. Can you have a function with 
non-variadic arguments followed by heterogeneous variadic 
arguments?


More information about the Digitalmars-d-learn mailing list