digitalmars.D.learn - Foreach over tuple of arrays?
- Sean Eskapp (21/21) Aug 07 2011 I have a tuple of arrays of different types, but want to call a template
- Philippe Sigaud (24/26) Aug 08 2011 I tried this with a delegate and a function template, it seems to work:
- Philippe Sigaud (17/17) Aug 08 2011 Hmm, I just saw your question on SO. Is that nearer to what you ask?
I have a tuple of arrays of different types, but want to call a template
function on each element. How would I do this?
void foo(T)(T elem)
{
...
}
I tried like this:
ArrayTuple!(T) data;
void iterate(alias func, uint n)()
{
static if(n < T.length)
{
foreach(elem; data[n])
func(elem);
iterate!(func, n + 1)();
}
}
Used like this:
iterate!(foo, 0)();
This doesn't work when passing a delegate as func, however. Is there a way to
circumvent this?
Aug 07 2011
Hi Sean,This doesn't work when passing a delegate as func, however. Is there a way to circumvent this?I tried this with a delegate and a function template, it seems to work: import std.typecons; void bar(T)(ref T elem) { elem = elem+1; } void main() { auto data = tuple([0,1,2,3], [3,2,1], [0,1]); auto foo = (ref int i){ i = i * i;}; writeln(data); foreach(index, range; data.expand) foreach(ref element; range) foo(element); writeln(data); foreach(index, range; data.expand) foreach(ref element; range) bar(element); writeln(data); } data.expand is only needed to get access to the underlying expression template in the 'data' tuple. Your own ArrayTuple!(T) may have other way to do that.
Aug 08 2011
Hmm, I just saw your question on SO. Is that nearer to what you ask?
It uses a anonymous template function:
import std.typecons;
void act(alias fun, T...)(ref Tuple!T data)
{
foreach(index, range; data.expand)
foreach(ref element; range)
fun(element);
}
void main()
{
auto data = tuple([0,1,2,3], [3,2,1], [0,1]);
writeln(data);
act!( (i) { return i+1; })(data);
writeln(data);
}
Philippe
Aug 08 2011









Philippe Sigaud <philippe.sigaud gmail.com> 