【发布时间】:2015-12-15 23:37:05
【问题描述】:
我目前正在阅读几本书以了解 c++14 的特性。我正在尝试使用可变参数模板将参数绑定到函数。我知道如何使用 std::bind 来做到这一点,但我也想用 c++14 lambda 表达式来实现这个函数,只是为了常识和理解,以及任何可能的性能优势。我读过 lambdas 可以内联,而 std::bind 不能内联,因为它是通过调用函数指针来实现的。
这是来自 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::forward': 2 个重载都不能转换所有参数类型
错误 C2198 'int (__cdecl &)(int,int)': 调用的参数太少
我认为当可变参数被转发到 lambda 时可能会发生错误,但我不太确定。
我的问题是如何正确地制定这段代码,以便我可以使用 lambda 来捕获函数及其参数,并在以后调用它。
【问题讨论】:
标签: c++ lambda c++14 variadic-templates variadic-functions