www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - iterate over variadic

reply FoxyBrown <Foxy Brown.IPT> writes:
How can we iterate over a variadic and have it's index. I'll do 
different things depend on if it's an even or odd index, but 
seems to be no way to get it.
Jul 09 2017
next sibling parent drug <drug2004 bk.ru> writes:
10.07.2017 01:21, FoxyBrown пишет:
 How can we iterate over a variadic and have it's index. I'll do 
 different things depend on if it's an even or odd index, but seems to be 
 no way to get it.
 
auto foo(Types...)() { foreach(T; Types) { // do what you need } } index could be added like usual
Jul 09 2017
prev sibling next sibling parent Lamex <Lamex dfghjkl.iuyt> writes:
On Sunday, 9 July 2017 at 22:21:59 UTC, FoxyBrown wrote:
 How can we iterate over a variadic and have it's index. I'll do 
 different things depend on if it's an even or odd index, but 
 seems to be no way to get it.
import std.stdio; import std.typecons, std.meta; template indexedAllSatisfy(alias F, T...) { bool doTest() { bool result = true; import std.range: iota; foreach(i; aliasSeqOf!(iota(0, T.length))) result &= F!(T[i], i, T.length); return result; } enum indexedAllSatisfy = doTest(); } unittest { template evenIntString(T, int index, int length) { static if (length & 1) enum evenIntString = false; else static if (index & 1) enum evenIntString = is(T == string); else enum evenIntString = is(T == int); } static assert(indexedAllSatisfy!(evenIntString, int, string, int, string)); static assert(!indexedAllSatisfy!(evenIntString, int , string, char, Object)); }
Jul 09 2017
prev sibling parent reply "H. S. Teoh via Digitalmars-d-learn" <digitalmars-d-learn puremagic.com> writes:
On Sun, Jul 09, 2017 at 10:21:59PM +0000, FoxyBrown via Digitalmars-d-learn
wrote:
 How can we iterate over a variadic and have it's index. I'll do
 different things depend on if it's an even or odd index, but seems to
 be no way to get it.
Easy: auto func(Args...)(Args args) { foreach (i, arg; args) { if (i % 2) { // even ... // do something with arg } else { // odd ... // do something with arg } } } T -- "Real programmers can write assembly code in any language. :-)" -- Larry Wall
Jul 10 2017
parent ag0aep6g <anonymous example.com> writes:
On 07/10/2017 08:31 PM, H. S. Teoh via Digitalmars-d-learn wrote:
 			if (i % 2) {
 				// even
odd
 				... // do something with arg
 			} else {
 				// odd
even
 				... // do something with arg
 			}
Jul 10 2017