我想构建一个 functon 模板,它采用任何函数指针及其参数列表 - 并返回一个(有状态的)lambda,它将这些参数值绑定(bind)到内部(想想 std::bind 但基于 lambda )
#include <iostream>
#include <vector>
template <class ...D>
class DEB;
template <class Ret, class ... Args>
auto getLambdaFromFunction(Ret(*func)(Args...)) {
return [func](Args ... ar){ // auto could work here but lambda is anyway templated by external template's Args
func(ar...);
};
}
template <class Ret, class ... Args>
auto wrapFunction(Ret(*func)(Args...),Args... args) {
return [=](){
func(args...);
};
}
int doone(int a, float b) {
std::cout << "do one";
return a;
}
int main() {
auto lw = getLambdaFromFunction(doone); // compiles
lw(1,2.); // invokation works
auto lambda_parameters_binded = wrapFunction(doone, 1,2.); // **ERROR**: no matching function for call
lambda_parameters_binded(); // see mom, no hands ie no arguments!
}
我相信我需要以某种方式在 wrapFunction 的 lambda 中捕获可变参数 默认的 [=] 捕获似乎不理解可变参数列表
最佳答案
您应该仔细阅读错误描述,现在函数接受 float,但您将 double 作为第三个参数传递。传递 float 将使其工作:
auto lambda_parameters_binded = wrapFunction(doone, 1, 2.0f);
另请注意,生成的 lambda 不返回任何内容,您应该在 lambda 主体内添加另一个 return 语句:
return
(
[=](void)
{
return(func(args...));
}
);
关于C++ 如何将可变参数函数模板的参数包 -> 包装到 lambda 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47428538/