Variadic function template

ref2401 refactor24 at gmail.com
Fri Jul 5 07:55:46 PDT 2013


I have a number of elements of type Data!int or Data!string,

class Data(TItem) {
	TItem _item;

	this(TItem item) {
		_item = item;
	}
}

which need to be packed into container Pack. Pack!int for 
Data!int and Pack!string for Data!string respectively.

class Pack(TItem) {
	string _name
	TItem[] _items;

	this(string name, size_t numOfItems) {
		_name = name;
		_items = new TItem[numOfItems];
	}
}

I'd like to have a function taking variable number of arguments 
of type Data!TItem that packs them into single container 
Pack!TItem, similar to this:

Pack!int p1 = pack("package1", new Data!int(24), new Data!int(78),
    new Data!int(147));
Pack!int p2 = pack("package2", new Data!int(-7), new Data!int(0),
    new Data!int(18), new Data!int(99), ... , new Data!int(128));
Pack!string p3 = pack("text pack 1", new Data!string("text1"),
    new Data!string("text2"), new Data!string("text3"));

I've tried several things but none of them works:
1) pack!(TItem, P = Data!TItems...)(string name, P params) { ... 
} 	
// compilation error

2) pack(TItem)(string name, Data!TItem...) { ... }	
// compilation error

3) pack!(P...)(string name, P params) { ... }	
// compiles, but I don't know how to get the type of parameters 
passed in.
//also I need to somehow check that all elements in 'params' have 
the same type Data!TItem

Please advise how to implement the function. Thanks.


More information about the Digitalmars-d-learn mailing list