dan*_*n h 3 c++ lambda variadic-functions variadic-templates c++14
我目前正在阅读一些书籍以了解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)...);
};
}
Run Code Online (Sandbox Code Playgroud)
这是我正在运行的主要代码:
#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;
Run Code Online (Sandbox Code Playgroud)
错误C2665'std :: forward':2个重载中没有一个可以转换所有参数类型
错误C2198'int(__ cdecl&)(int,int)':调用的参数太少
我认为当可变参数转发到lambda时可能会发生错误,但我不太确定.
我的问题是如何正确地制定这个代码,以便我可以使用lambda来捕获函数及其参数,并在以后调用它.
我已经读过lambdas可以内联而std :: bind不能内联,因为它是通过调用函数指针来实现的.
如果你传递simpleAdd给然后绑定参数的东西,那么你是否使用bind并不重要.你觉得lambda有func什么用?这是一个函数指针.
lambda-vs-function-pointer案例是关于写作bind(simpleAdd, 2, 3)与[] { return simpleAdd(2, 3); }.或结合的λ状[](auto&&...args) -> decltype(auto) { return simpleAdd(decltype(args)(args)...); }与结合simpleAdd直接(将使用函数指针).
无论如何,实施它是非常棘手的.你不能使用by-reference capture,因为事情很容易晃来晃去,你不能使用简单的按值捕获,因为即使是rvalues也会复制参数,你不能在init中进行包扩展-捕获.
这遵循了std::bind语义(调用函数对象并将所有绑定参数作为左值传递),除了1)它不处理占位符或嵌套绑定,以及2)函数调用运算符总是const:
template<class Func, class ...Args>
inline decltype(auto) funcLambda(Func && func, Args && ...args)
{
return [func = std::forward<Func>(func),
args = std::make_tuple(std::forward<Args>(args)...)] {
return std::experimental::apply(func, args);
};
}
Run Code Online (Sandbox Code Playgroud)
cppreference有一个实现std::experimental::apply.
请注意,这并解开reference_wrapperS,喜欢bind,因为make_tuple做的.
你的原始代码崩溃了,因为args它const位于lambda的函数调用操作符(const默认情况下),forward最终试图抛弃constness.
| 归档时间: |
|
| 查看次数: |
3091 次 |
| 最近记录: |