2016-12-31 51 views
9

我有一個功能叫的地方是x返回一個值,知道並已知參數:如何檢索要在模板中使用的函數的返回類型?

int x(int y); 

我有別的地方,我想創建一個容器包含此功能的n調用。然後我想多次執行它。

問題是,我不想依靠它是一個int返回類型。我需要在編譯時推導出返回類型。例如:

std::vector<result_of<x(int)>::type> results; 

但我不想指定參數值,因爲它們是靜態的。

+0

[This StackOverflow question](http://stackoverflow.com/questions/11310898/how-do-i-get-the-type-of-a-variable)可能會回答你的問題。 – Nietvoordekat

+0

你可以看看這裏的解決方案:http://stackoverflow.com/a/41301717/2378300 – Jonas

回答

6

您可以創建自己的特質,是這樣的:

template <typename F> struct my_result_of; 

template <typename F> struct my_result_of<F*> : my_result_of<F> {}; 

template <typename Ret, typename ... Ts> 
struct my_result_of<Ret(Ts...)> 
{ 
    using type = Ret; 
}; 

template <typename F> using my_result_of_t = typename my_result_of<F>::type; 

而且使用它像(假設沒有x重載):

std::vector<my_result_of_t<decltype(x)>::type> results; 
5

你就近了。假設T是調用函數的模板參數:

std::vector<decltype(x(std::declval<T>()))> results; 
+1

[這是行不通的。](http://coliru.stacked-crooked.com/a/755fc639873ce270)你測試你的解決方案? – cpplearner

+1

@cpplearner:你的觀點。這不是result_of的工作原理。更改爲「decltype」。 – erenon

+0

「調用者函數的模板參數」?希望調用'x'的函數沒有模板參數。 – NeomerArcana

2

可以濫用std::function::result_type

int x(int y); 
static_assert(std::is_same_v<int,std::function<decltype(x)>::result_type>); 

當然,如果x是一個真正的函數,這隻會工作。如果x是一個任意的函數對象,那麼它的結果類型可能依賴於它的參數類型,在這種情況下,如果不指定參數,你就無法知道它的結果類型。

2

我假設你最多可以使用到最新標準版本,因爲你沒有指定它。
下面是一個最小的,工作示例:

#include<vector> 
#include<functional> 
#include<utility> 

template<std::size_t... I, typename F, typename... A> 
auto gen(std::index_sequence<I...>, F &&f, A... args) { 
    return std::vector<decltype(std::forward<F>(f)(args...))>{ 
     (I, std::forward<F>(f)(args...))... 
    }; 
} 

template<std::size_t N, typename F, typename... A> 
auto gen(F &&f, A... args) { 
    return gen(std::make_index_sequence<N>{}, std::forward<F>(f), args...); 
} 

int f(int, char) { return 0; } 

int main() { 
    auto vec = gen<10>(&f, 0, 'c'); 
} 

你的函數的返回類型是很容易推導出:

decltype(std::forward<F>(f)(args...)) 

我想創建一個容器含有N此函數的調用。然後我想多次執行它。

爲此,我使用std::index_sequence來創建具有正確尺寸的參數包。

(I, std::forward<F>(f)(args...))... 

的基本思想是利用逗號運算符來解壓上述參數包並執行N倍功能:
然後載體本身,因爲它遵循被初始化。調用f返回的值用於填充矢量。

請注意,args不完美轉發到f
第一次執行期間消耗的可移動對象可能會導致問題。

相關問題