Is there kind of "associative tuple" - like syntax in D?

Justin Whear justin at economicmodeling.com
Fri Feb 21 11:37:37 PST 2014


On Fri, 21 Feb 2014 19:09:56 +0000, Uranuz wrote:


>> You could do something like this:
>>
>> alias Foo!(
>>     OptionType.optType1, 100, OptionType.optType2, "example,
>>     ...etc...
>> ) MyFoo;
> 
> Yes. I already use this. But it makes it not semanticaly obvious that
> OptionType.optType1 is a kind of `key` and 100 is `value`. Also it needs
> to parse it and check for correctness that you have `key` and
> corresponding value. Also code that realize parsing could shadow main
> logic of class/function. Another point is that `key`: `value` form is
> easier to read than sequence of some values separated by ','. You often
> need to move every key-value pair to single line to make it readeble.
> 
> May be it's just syntactic sugar and isn't looking in D'ish way or
> something.

I can't think of any way to get `:` or `=` to indicate assignment here.  
This is as clean as I could get things in 10 minutes (runs with `rdmd -
main`):


enum OptionType
{
	Option1,
	Option2
}

struct OptionPair(OptionType opt, T)
{
	enum option = opt;
	T value;

	this(T v)
	{
		value = v;
	}
}

class Foo(Opts...)
{
	// Prove it works
	static this()
	{
		import std.stdio;
		foreach (opt; Opts)
			writeln(opt.option, " = ", opt.value);
	}
}

alias opt1 = OptionPair!(OptionType.Option1, int);
alias opt2 = OptionPair!(OptionType.Option2, string);

alias MyFoo = Foo!(opt1(23), opt2("foo"));


More information about the Digitalmars-d-learn mailing list