Changing Template Static Ifs to Recursion

jmh530 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed May 31 14:02:07 PDT 2017


On Wednesday, 31 May 2017 at 19:22:18 UTC, Stefan Koch wrote:
>
> You could also use string mixins.
> Which will be more efficient then recursion.

I try to avoid string mixins unless I can't help it. 
Nevertheless, I made an effort to try to get it to work and below 
seems to be working. I still have to use some recursion to 
generate the string.

The downside is that this version can't be @nogc, correct?


auto ref opIndex(Slices...)(Slices slices)
	if (Slices.length == Types.length)
{
	template GetParensi(size_t i)
	{
		const char[] GetParensi = "this.underlying[" ~ i.stringof ~
										"][slices[" ~ i.stringof ~ "]]";
	}

	template GenParens(T...)
	{
		static if (T.length > 0)
		{
			static if (T.length == 1)
				const char[] GenParens = GetParensi!(T.length - 1);
			else static if (T.length > 1)
				const char[] GenParens = GenParens!(T[0 .. $ - 1]) ~ ", " ~
												GetParensi!(T.length - 1);
		}
	}
	
	const char[] GenResult = "foo!(Names)(" ~ GenParens!Slices ~ ")";
	
	return mixin(GenResult);
}


More information about the Digitalmars-d-learn mailing list