2015-06-21 95 views
2

我有一個模板參數接受另一個函數的函數。在這個函數中,我想調用一個不同的模板函數,它需要使用函數參數的返回類型實例化。確定作爲模板參數給出的函數的返回類型

因爲我可能搞砸最後一段,讓我嘗試用一​​個例子來闡明:

template <typename funT> 
void foo(funT function_to_call) 
{ 
    auto data = bar<funT::return_value>(); 
    /// do some stuff with data. 
    /// call function_to_call, but bar needed to be called first. 
} 

如何獲得凡特:: RETURN_VALUE?

非常感謝,

+0

這個問題已經被市場視爲一個不相關的市場的副本,不是嗎? – rems4e

+0

是的,就我所知,答案與我的問題無關,除非它們都與C++模板有關。 – Spacemoose

+0

無論如何,只要'funT'不帶任何參數,您可以使用'std :: result_of :: type'來訪問返回類型。 – rems4e

回答

1

你可以使用特別std::result_of型性狀的方式如下:

template <typename funT> 
void foo(funT function_to_call) { 
    auto data = bar<typename std::result_of<decltype(function_to_call)&()>::type>(); 
    //... 
} 

LIVE DEMO

你也可以進一步推廣到接受任何形式的功能,沿其通過使用可變參數模板以下列方式輸入參數:

template <typename funT, typename ...Args> 
void foo(funT function_to_call, Args... args) { 
    auto data = bar<typename std::result_of<funT(Args...)>::type>(); 
    ... 
} 

LIVE DEMO

+2

這與僅使用'decltype(function_to_call())'有什麼區別嗎? – Alejandro

+0

@Alejandro是的,因爲'decltype(function_to_call())'返回到'function_to_call'返回類型(例如'int')並且調用'std :: result_of :: type'會給你一個編譯錯誤。 – 101010

+0

我只是在談論用'decltype(function_to_call())'替換'typename std :: result_of :: type''。事實上,它確實有效!看看[這個現場演示](http://coliru.stacked-crooked.com/a/c4b297ff50d458cf)。 – Alejandro

0

您可以使用typename std::result_of<funT()>::type滿足您的需求,或者std::result_of_t<funT()>如果你有機會到C++ 14。

1

除了像其他人所建議的那樣使用result_of之外,您還可以使用decltype

對於那些function_to_call不接受任何參數的情況下,你可以做到以下幾點:

auto data = bar<decltype(function_to_call())>(); 

然而,一個更通用的情況下,作爲@ 101010已經指出的那樣,你可以有你的函數接受任何數目的參數。生成的代碼是這樣的:

template <typename funT, typename ...Args> 
void foo(funT function_to_call, Args&&... args) 
{ 
    auto data = bar<decltype(function_to_call(std::forward<Args>(args)...))>(); 
} 

的情況外,我已經試過了,decltypestd::result_of有關於如果傳遞函數類型返回正確的類型相同的功能不是指針正如@hvd所指出的那樣。通過g ++來源看,std::result_of通常按decltype來實現,對於上述情況。

儘管C++ 14 std::result_of_t選項也非常有吸引力,對我來說,使用這個選項似乎比替代選項typename std::result_of<...>::type更清晰和更具可讀性。

相關問題