Thread overview | |||||
---|---|---|---|---|---|
|
August 07, 2011 Foreach over tuple of arrays? | ||||
---|---|---|---|---|
| ||||
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? |
August 08, 2011 Re: Foreach over tuple of arrays? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Sean Eskapp | 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.
|
August 08, 2011 Re: Foreach over tuple of arrays? | ||||
---|---|---|---|---|
| ||||
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 |
Copyright © 1999-2021 by the D Language Foundation