dlang语言以下代码:void testtargtarg hello foreachv;hello writelnvtypeidv==typeidstring; int test1string funcName writelnfuncName; import corevararg; int sum = 0; for int i = 0;
test函数涉及到了泛型,其中参数targ使用了泛型。
test1函数也涉及到了泛型,其中使用了core.vararg库中的va_arg模板函数来获取可变参数列表中的参数类型,参数列表使用了...表示可变参数。
test3函数也涉及到了泛型,其中参数targ使用了泛型,同时使用了模板字符串来指定函数名。
以下是一个完整的示例代码,展示了泛型函数的不同写法及用法:
void test(targ...)(targ hello)
{
foreach(v;hello)
{
writeln(v,":",typeid(v)==typeid(string));
}
}
int test1(string funcName,...)
{
writeln(funcName);
import core.vararg;
int sum = 0;
foreach(arg; va_args)
{
static if(is(typeof(arg) == int)))
{
sum += arg;
}
}
return sum;
}
int test2(int[] one...)
{
int sum = 0;
foreach(v;one)
{
sum += v;
}
return sum;
}
void test3(string wudi,targ...)(targ hello)
{
writeln(wudi);
foreach(v;hello)
{
writeln(v,":",typeid(v)==typeid(string));
}
}
void main()
{
// test函数的调用
test(1,"2"); // 输出:1:false 2:true
writeln("-----------------------------------------");
// test1函数的调用
auto one = test1("hello",1,2,"wudi",3); // 输出:hello 6
writeln(one);
writeln("-----------------------------------------");
// test2函数的调用
auto two = test2(5,6,7); // 输出:18
writeln(two);
writeln("-----------------------------------------");
// test3函数的调用
test3!"jj"(1,2,3); // 输出:jj 1:false 2:false 3:false
}
在示例代码中,test1函数的写法使用了static if来判断参数类型是否为int,而不是使用typeid函数比较类型,这是一种更加优雅的写法
原文地址: http://www.cveoy.top/t/topic/fNq1 著作权归作者所有。请勿转载和采集!