6

我有很長的模板函數聲明:我可以使用decltype()來避免顯式模板實例中的代碼重複嗎?

template <typename T> void foo(lots ofargs, goin here, andeven more, ofthese arguments, they just, dont stop); 

,沒有超載。我想明確地實例化它。我可以寫(說了T = int):

template void foo<int>(lots ofargs, goin here, andeven more, ofthese arguments, they just, dont stop); 

但我真的不希望複製長的聲明。我本來喜歡能夠這樣說:

template <typename T> using bar = decltype(foo<T>); 

然後:

template bar<int>; 

現在,第一行編譯(GCC 4.9.3),但第二行沒有按」噸。我可以讓它工作嗎?或者我可以使用decltype()其他方式避免複製實例的聲明?

注意:我使用了一個例子,在這個例子中,你不能只從參數中推斷出類型,因爲我想要任何解決方案來支持這種情況。

回答

3

當然。從[temp.explicit]:

爲顯式實例的語法是:
        顯式實例化
               的extern 選擇template聲明

[...]如果顯式實例化一個函數或成員函數,在聲明中不合格-ID須爲模板id或者,所有的模板參數可以推斷,一個 模板名稱operator-function-id[注:聲明可以宣佈合格-ID,在這種情況下合格-ID不合格-ID必須是模板id- 結束]

我們需要一個聲明。讓我們假設,我們開始用:

template <class T> void foo(T) { } 

我們可以通過只明確專注:

template void foo<char>(char); // template-id 
template void foo(int);   // or just template-name, if the types can be deduced 

這是一樣寫過:

using Fc = void(char); 
using Fi = void(int); 

template Fc foo<char>; 
template Fi foo; 

這是一樣的有書面:

template <class T> using F = decltype(foo<T>); 

template F<char> foo<char>; 
template F<int> foo; 

基本上,template bar<int>不起作用的原因是它不是一個聲明。你也需要這個名字。

+0

我在編輯這個問題,以確保你不能推導出函數參數的模板參數,這正是我真正感興趣的。我只是撒了一個T t來衡量好,並不意味着爲你使用它...如果你的答案仍然相關,那麼很好。 – einpoklum

+0

@einpoklum這個問題並不是很清楚,你爲什麼認爲我的答案不相關? – Barry

+0

我沒有說這是無關緊要的,我只是有一種感覺(在你最後一次編輯之前),你可能比你更依賴它。 – einpoklum