Array of structs construction

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Oct 19 22:42:08 PDT 2012


On Fri, Oct 19, 2012 at 10:32:48PM -0700, H. S. Teoh wrote:
> On Sat, Oct 20, 2012 at 03:06:56AM +0200, bearophile wrote:
> > I'd like to write code like this (the constructors of the structs
> > must take 1 argument):
> > 
> > // some imports here
> > void main() {
> >     BigInt[] data1 = [5, 6, 9];
> >     Ranged!(int,5,10)[] data2 = [5, 6, 9];
> >     Nibble[] data3 = [1, 2, 15]; // Nibble.sizeof == 1
> >     alias Typedef!int Mint;
> >     Mint[] data4 = [5, 6, 9];
> > }
> > 
> > 
> > Do you like this feature?
> [...]
> 
> What about mixin() with a CTFE function that expands an array of
> initializers at compile-time? Something like:
[...]

OK, here's a tested, working example:

	import std.stdio;
	string structArray(S)(string[] args...) {
		string s = "[";
		string delim = "";
		foreach (a; args) {
			s ~= delim ~ S.stringof ~ "(" ~ a ~ ")";
			delim = ",";
		}
		return s ~ "]";
	}
	struct AStruct {
		int x, y;
	}
	void main() {
		AStruct[] arr = mixin(structArray!AStruct("1,1", "1,2", "2,2", "2,3"));
		writeln(arr);
	}


T

-- 
"Life is all a great joke, but only the brave ever get the point." -- Kenneth Rexroth


More information about the Digitalmars-d mailing list