2011-10-31 50 views
6

tl; dr:你如何在D中做perfect forwardingD完美轉發?


鏈接有一個很好的解釋,但是,例如,讓我們說我有這樣的方法:

void foo(T)(in int a, out int b, ref int c, scope int delegate(ref const(T)) d) 
    const nothrow 
{ 
} 

如何創建另一種方法,bar(),它可以代替foo()被調用,後者隨後調用foo()「完美」(即不在呼叫站點引入編譯/範圍/等問題)?

簡易方法

auto bar(T...)(T args) 
{ 
    writeln("foo() intercepted!"); 
    return foo(args); 
} 
當然

不起作用,因爲它不處理refinoutinoutconst -ness方法,pure -ity,nothrow等...並且還限制了值可以如何與r值一起使用。

我不知道如何處理這些可能的情況......任何想法?

回答

3

你幼稚的做法可以改進,但它仍然不是很完美:

auto ref bar(T...)(auto ref T args) 
{ 
    writeln("foo() intercepted!"); 
    return foo(args); 
} 

現在唯一的問題是scope參數。

+1

等一下,nothrow','pure','const','inout','@ property','@ safe'和所有其他的事情我現在還想不到?這些(甚至是'@ property')中的每一個都可以稍微改變代碼行爲,並且/或者防止編譯。 – Mehrdad

+1

你需要一個自動引用作爲返回,並且如果你的模板需要considition,而且我仍然不確定這是否足夠。 – deadalnix

+0

@Mehrdad:好點,儘管現在對模板的推導是純粹的。 – dsimcha