我需要执行N次动作。 D的最佳方式是什么?
for(uint i=0; i<N; i++)
action();
foreach(uint i; 0.. N)
action();
也许更好的东西?理想情况下,我想要一些像Groovy&Ruby&#39; times
这样的东西,例如
N.times {
action();
}
有可能吗?
答案 0 :(得分:10)
是的,有可能
import std.stdio;
import std.traits;
void foo()
{
writeln("Do It!");
}
void times(T,N)(N n, T action) if (isCallable!T && isIntegral!N)
{
static if (ParameterTypeTuple!action.length == 1
&& isIntegral!(ParameterTypeTuple!action[0]))
foreach (i; 0 .. n)
action(i);
else
foreach (i; 0 .. n)
action();
}
void main(string[] args)
{
10.times(&foo);
10.times({writeln("Do It!");});
10.times((uint n){writeln(n + 1, " Round");});
}
支持参数的版本:
import std.stdio;
import std.traits;
void foo()
{
writeln("Do It!");
}
struct Step {
alias n this;
size_t n;
this(size_t i)
{
n = i + 1;
}
}
struct Index {
alias n this;
size_t n;
}
void times(T,N,A...)(N n, T action, A args) if (isCallable!T && isIntegral!N)
{
alias PTTAction = ParameterTypeTuple!action;
static if (PTTAction.length >= 1)
{
alias FP = PTTAction[0];
static if (is(Index == FP) || is(Step == FP))
foreach (i; 0 .. n)
action(FP(i), args);
else
action(args);
}
else
foreach (i; 0 .. n)
action();
}
void main(string[] args)
{
10.times(&foo);
10.times({writeln("Do It!");});
10.times((Step n){writeln(n, " Step");});
10.times((Index n, string msg){writeln(n, msg);}, " Index");
stdin.readln;
}
<强>更新强>
为了获得更好的性能,您可以使用别名模板参数进行操作:
void times(alias action,N)(N n) if (isCallable!action && isIntegral!N)
{
static if (ParameterTypeTuple!action.length == 1
&& isIntegral!(ParameterTypeTuple!action[0]))
foreach (i; 0 .. n)
action(i);
else
foreach (i; 0 .. n)
action();
}
void main(string[] args)
{
10.times!(foo);
10.times!({writeln("Do It!");});
10.times!((uint n){writeln(n + 1, " Round");});
}
答案 1 :(得分:4)
也许是这样的?
void loop(int n, void delegate() func)
{
foreach (i; 0 .. n)
{
func();
}
}
用法:
loop(10, {
writeln("Hello World!");
});