D-如果变量参数不能正常工作,则为静态
假设我有下面的变量函数,它的任务是从片段(每个片段可以是整数类型的索引,也可以是字符串类型的节点)将路径连接在一起: 如果我以后像这样使用它:D-如果变量参数不能正常工作,则为静态,d,D,假设我有下面的变量函数,它的任务是从片段(每个片段可以是整数类型的索引,也可以是字符串类型的节点)将路径连接在一起: 如果我以后像这样使用它:stringpath=makePath(“foo”,“bar”),那么代码会以某种方式到达静态断言(0),编译终止。这是最奇怪的,但是pragma实际上将string作为第一个参数的类型写入,尽管使用了其他类型的代码路径 更好的是,使用makePath(12,13)会导致编译器同时抱怨字符串行(关于int和string的不兼容类型)和静态断言。这是怎么回事
stringpath=makePath(“foo”,“bar”)
,那么代码会以某种方式到达静态断言(0)代码>,编译终止。这是最奇怪的,但是pragma实际上将string
作为第一个参数的类型写入,尽管使用了其他类型的代码路径
更好的是,使用makePath(12,13)
会导致编译器同时抱怨字符串行(关于int
和string
的不兼容类型)和静态断言
。这是怎么回事
我在DMD和LDC上都试过了。这里的错误是关键字。(我发现这是一个令人困惑的关键词…)
我建议您使用std.traits中的模板来测试类型,其中大部分包括:
以下是您的函数的工作版本:
string
makePath(P...)(P path)
{
import std.conv;
import std.format;
import std.traits : isSomeString, isNumeric;
string res;
foreach (piece; path) {
static if (isNumeric!(typeof(piece)))
res = res is null ? piece.to!string : format("%s[%s]", res, piece);
else static if (isSomeString!(typeof(piece))) // Note, you were missing the 'static' on the 'else if' part
res = res is null ? piece : format("%s.%s", res, piece);
else
static assert(0);
}
return res;
}
unittest {
static assert(makePath("foo","bar") == "foo.bar");
static assert(makePath("foo","bar",1) == "foo.bar[1]");
}
第一个else if
应该是else static if
。这是您的原始代码中的错误还是仅此而已?@AdamD.Ruppe是的,这是原始代码中的错误(您已经指出这是一个非常愚蠢的错误)。
string
makePath(P...)(P path)
{
import std.conv;
import std.format;
import std.traits : isSomeString, isNumeric;
string res;
foreach (piece; path) {
static if (isNumeric!(typeof(piece)))
res = res is null ? piece.to!string : format("%s[%s]", res, piece);
else static if (isSomeString!(typeof(piece))) // Note, you were missing the 'static' on the 'else if' part
res = res is null ? piece : format("%s.%s", res, piece);
else
static assert(0);
}
return res;
}
unittest {
static assert(makePath("foo","bar") == "foo.bar");
static assert(makePath("foo","bar",1) == "foo.bar[1]");
}