我目前正在閱讀幾本書以抓住C++ 14的特性。我正在嘗試使用可變參數模板將參數綁定到函數。我知道如何使用std :: bind來做到這一點,但我也想用C++ 14 lambda表達式來實現這個功能,只是爲了常識和理解,以及任何可能的性能優勢。我讀過lambda表達式可以內聯,而std :: bind不能內聯,因爲它通過調用函數指針發生。C++ 14函數綁定的可變參數lambda捕獲
下面是從myFunctions.h代碼:
#include <functional>
int simpleAdd(int x, int y) {
return x + y;
}
//function signatures
template<class Func, class... Args>
decltype(auto) funcBind(Func&& func, Args&&...args);
template<class Func, class... Args>
decltype(auto) funcLambda(Func&& func, Args&&...args);
/////////////////////////////////////////////////////////////////
//function definitions
template<class Func, class... Args>
inline decltype(auto) funcBind(Func&& func, Args&&... args)
{
return bind(forward<Func>(func), forward<Args>(args)...);
}
template<class Func, class ...Args>
inline decltype(auto) funcLambda(Func && func, Args && ...args)
{ //The error is caused by the lambda below:
return [func, args...]() {
forward<Func>(func)(forward<Args>(args)...);
};
}
這裏是我運行的主要代碼:
#include<iostream>
#include<functional>
#include "myFunctions.h"
using namespace std;
int main()
{
cout << "Application start" << endl;
cout << simpleAdd(5,7) << endl;
auto f1 = funcBind(simpleAdd,3, 4);
cout << f1() << endl;
//error is occurring below
auto f2 = funcLambda(simpleAdd, 10, -2);
cout << f2() << endl;
cout << "Application complete" << endl;
錯誤C2665 '的std ::前進':沒有2個重載可以轉換所有的參數類型
錯誤C2198 'INT(__cdecl &)(INT,INT)':呼叫
參數太少我認爲錯誤可能發生在可變參數被轉發到lambda時,但我並不確定。
我的問題是我如何正確地制定這段代碼,以便我可以使用lambda捕獲函數及其參數,並在稍後調用它。
謝謝你的回答。使用lambda捕獲作爲使用std :: bind的複雜性比我期待的要複雜得多。從cppreference.com申請和調用,但我收到一些更多的編譯器錯誤:錯誤\t C2893 \t無法專門化func (_Callable &&,_ Types && ...)',以及錯誤\t C2975 \t'_Size':'std :: make_index_sequence'的無效模板參數,預期的編譯時常量表達式。稍後我會再看一遍,但現在我會堅持使用綁定。 –