How in the name of D do you deal with more than one optional template parameter?

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Oct 30 21:19:13 UTC 2018


On Tue, Oct 30, 2018 at 08:46:31PM +0000, aliak via Digitalmars-d-learn wrote:
> Hi,
> 
> Do you guys have any strategies for dealing with templates when they
> have more than one optional  parameter?
> 
> E.g let's say we have a type C that takes three parameters
> 
> struct B(T) {}
> struct C(string name, T, string desc) {}
> 
> And let's say I want T and desc to be optional and T should be of type
> B, i.e. I would want to be able to do is this:
> 
> auto x = C!("name", B!int)();
> auto y = C!("name", B!int, "desc")();
> auto z = C!("name", "desc")();
> 
> So C is a template that must have a name, and can optionally have a B,
> or a description, or both.
> 
> The immediate (maybe naive) way that comes to mind is:
> 
> struct C(string name, rest...)
> if (rest.length <= 2)
> if (rest has one elements then it can be either template B or a string) //
> how?
> if (rest has two elements then it must be template B followed by string) //
> how?

	struct C(Args...)
	if ((rest.length == 2 && is(Args[0] == B!C, C) && is(Args[1] == string)) ||
	    (rest.length == 1 && (is(Args[0] == B!C, C) || is(Args[0] == string))))
	{
		...
	}


[...]
> Giving it some more thought, one could do this too:
> 
> struct Void {}

This is unnecessary.  Why not just use `void` directly?

	struct C(string name, T, string desc)
		if (is(T : B!C, C) || is(T == void))
	{
		...
	}


> Are there other ways? Or does anyone have any tips on how to deal with
> this?  Or is the alias way generally the way to go?
[...]

You can also use default parameters for templates:

	struct C(string name, T, string desc = null)
	{
		...
	}

then you just need one more alias for the string-only variant:

	alias C(string name, string desc) = C!(name, void, desc);

Note that this syntax is much shorter than the full eponymous template
syntax, which makes it easier to deal with longer parameter lists:

	struct ManyParams(A a, B b=defaultB, C c=defaultC, D d=defaultD)
	{
		...
	}
	alias ManyParams(A a, C c, D d=defaultD) = ManyParams!(a, null, c, d);
	alias ManyParams(A a, D d=defaultD) = ManyParams!(a, void, void, d);

And so on.

And there's probably a way to auto-generate those alias templates if you
anticipate needing to do this many times. (Or if you're insane and want
to let the user specify different arguments in any order.) Mixins and
CTFE codegen FTW!  :-D


T

-- 
A mathematician is a device for turning coffee into theorems. -- P. Erdos


More information about the Digitalmars-d-learn mailing list