2012-03-09 126 views
5

我试图将D的sort函数作为模板参数发送到pipe函数。当我使用sort没有模板参数工作原理: 将模板化函数作为参数发送到D中的模板函数

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"?对于我想要做的事情,有没有正确的语法?

UPDATE

OK,我试图包裹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需要?

回答

5

是的,这是因为额外的模板参数 - 特别是Range参数。这个问题可以降低到

size_t sort2(alias f, Range)(Range range) 
{ 
    return 0; 
} 
alias sort2!"b<a" u; 

实例化sort!"b<a"将失败,因为范围并不确定。函数调用sort2!"b<a"([1,2,3])的工作原理是因为参数[1,2,3]可以告诉编译器类型范围是int[]。这被称为“隐式函数模板实例化(IFTI)”。但IFTI只在用作功能时才起作用。在你的用例中,sort!"b<a"被实例化而不提供所有参数,因此是错误。

这可以通过固定使输入函数文本,这仅仅是类似于您mysort解决方案:

auto arr = pipe!(x => sort!"b<a"(x))([1,3,2]); 

或者你可以提供所有必需的模板参数。这使得代码非常难以阅读。

auto arr = pipe!(sort!("b<a", SwapStrategy.unstable, int[]))([1,3,2]); 
+0

我看看......我想通了'pipe'模板,隐式得到的参数作为模板参数的类型,应传递参数给第一管道的功能,但我看并非如此。 – 2012-03-10 19:17:06

+0

@IdanArye:'pipe'永远不会这样做,因为可以将它从参数中分离出来('alias pipe!(f)piped;'然后多行''pipeped([1,2,3]);') – kennytm 2012-03-10 19:54:42

+0

不应该像''别名'使'管道'模板功能本身? – 2012-03-10 21:48:16