2012-03-09 127 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