【发布时间】:2012-03-27 05:24:08
【问题描述】:
我正在尝试将 D 的 sort 函数作为模板参数发送给 pipe 函数。当我使用不带模板参数的sort 时,它可以工作:
import std.stdio,std.algorithm,std.functional;
void main()
{
auto arr=pipe!(sort)([1,3,2]);
writeln(arr);
}
但是,当我尝试将 sort 与模板参数一起使用时:
import std.stdio,std.algorithm,std.functional;
void main()
{
auto arr=pipe!(sort!"b<a")([1,3,2]);
writeln(arr);
}
我收到一个错误 - main.d(5): Error: template instance sort!("b<a") sort!("b<a") does not match template declaration sort(alias less = "a < b",SwapStrategy ss = SwapStrategy.unstable,Range)
为什么会这样? sort!"b<a" 独立工作,它具有与sort 相同的参数和返回类型,那么为什么pipe 接受sort 而不是sort!"b<a"?我尝试做的事情有正确的语法吗?
更新
好的,我已尝试包装 sort 函数。以下代码有效:
import std.stdio,std.algorithm,std.functional,std.array;
template mysort(string comparer)
{
auto mysort(T)(T source)
{
sort!comparer(source);
return source;
}
}
void main()
{
auto arr=pipe!(mysort!"b<a")([1,3,2]);
writeln(arr);
}
那么为什么原始版本不起作用?这是因为sort 需要额外的模板参数吗?
【问题讨论】: