2017-03-15 132 views
-1

我正在嘗試編寫一個頭文件,其中包含一個調用main.cpp中的函數並轉發任意數量參數的函數。此代碼的返回類型需要與轉發函數的返回類型相匹配。爲了達到這個目的,我編寫了下面的虛擬程序,但是我無法得到它來編譯。我會一些幫助感激:根據轉發函數的類型推斷的模板返回類型

#include <functional> 
#include <iostream> 

double f(double x, int params) { 
    return 1; 
} 

template <typename func, typename... Args> 
double test(std::function<func(double, Args...)> predicate, Args&&... params){ 
    return 2; 
} 

int main() { 
    int dummy = 1; 
    double result = test(&f, dummy); 
    std::cout<<result<<std::endl; 
    return 0; 
} 

編譯器(鐺++ - 3.8)提供了以下錯誤:

test.cpp:15:18: error: no matching function for call to 'test' 
     double result = test(&f, dummy); 
        ^~~~ 
test.cpp:9:8: note: candidate template ignored: could not match 
     'function<type-parameter-0-0 (double, type-parameter-0-1...)>' against 
     'double (*)(double, int)' 
double test(std::function<func(double, Args...)> predicate, Args&&... params){ 
    ^
1 error generated. 
+0

請編輯您的問題,方法是刪除所有不必要的代碼和註釋,並添加編譯器給出的確切錯誤消息。 – YSC

回答

2

如何:

#include <utility> 

template <typename F, typename ...Args> 
auto test(F&& f, Args&&... args) 
    -> decltype(std::forward<F>(f)(std::forward<Args>(args)...)) { 
    return std::forward<F>(f)(std::forward<Args>(args)...); 
} 

用法:

test(f, j, dummy); 

在C++ 14中,你可以寫這個mor e簡單如下:

template <typename F, typename ...Args> 
decltype(auto) test(F&& f, Args&&... args) { 
    return std::forward<F>(f)(std::forward<Args>(args)...); 
} 
+0

謝謝,這非常有幫助,我在文章中沒有提到的是頭文件引入了一個傳遞給轉發函數的新變量。我試過'template auto test(F && f,Args && ... args) - > decltype(std :: forward (f)(double,std :: forward ( args)...)){double x = 3.2; return std :: forward (f)(x,std :: forward (args)...); (f)(double),std(std :: }''但我現在得到編譯器錯誤'test.cpp:16:42:error:expected'('for function-style cast or type construction - > decltype(std :: forward ::前向(args)...)){' – AlexD

+0

@AlexD:'decltype(std :: forward (f)(42。,std :: forward (args)...))'或'decltype (std :: forward (f)(std :: declval (),std :: forward (args)...))' – Jarod42

+0

@ Jarod42謝謝,現在明白了:) – AlexD