On Saturday, 7 July 2018 at 08:09:51 UTC, vino.B wrote:
Hi All,
Request you help, on the below code
import std.stdio: writeln;
void process(T ...)(string ID, T args) {
if (ID == "I1") { writeln(args.length, "\t", args[0]); }
else if (ID == "I2") { writeln(args.length, "\t", args[1]);}
}
void main() {
string S1 = "Test1", S2 = "Test2", ID1 = "I1", ID2 = "I2";
int Size = 1;
process(ID1, S1);
process(ID2, S2, Size);
}
Error:
Test.d(5): Error: array index [1] is outside array bounds [0 ..
1]
Test.d(11): Error: template instance `Test.process!string`
error instantiating
From,
Vino.B
Ok, the problem here is, that as args (and especially its length)
are known at compile time, args are checked for having enough
length in all cases of the run time parameter.
My question would be, why do you need the ID string, if you know
what to print from the length of args?
´´´
void process2(T ...)(string ID, T args)
{
static if(args.length == 1)
{
if (ID == "I1")
{
writeln(args.length, "\t", args[0]);
}
}
else static if(args.length == 2)
{
if (ID == "I2")
{
writeln(args.length, "\t", args[1]);
}
}
}
void main()
{
string S1 = "Test1", S2 = "Test2", ID1 = "I1", ID2 = "I2";
int Size = 1;
process2(ID1, S1);
process2(ID2, S2, Size);
}
´´´