如何从lambda表达式派生参数?

use*_*129 3 c++ lambda c++11

如何更改模板函数定义以使其起作用?

请考虑以下代码:

#include <iostream>

#include <functional>

using namespace std;

void callthis(function<void()> func){
    func();
}

void callthis(function<void(int)> func, int par){
    func(par);
}


template<typename... Args>
void callthistemp(function<void(Args...)> func, Args&&... args){
    func(std::forward<Args>(args)...);
}

int main(){

callthis([](){cout << "hello " << endl;}); // (1)
callthis([](int x)->void{cout << "hello " << x << endl;},1); //(2)
function<void(int)> xx = [](int x){cout << "hello" << endl;};
callthistemp(xx,1);//(3)

//callthistemp([](int x)->void{cout << "hello" << endl;},1); //(4)
//callthistemp<int>([](int x)->void{cout << "hello" << endl;},1); //(5)
}
Run Code Online (Sandbox Code Playgroud)

前三个案例都运行良好,但最后两个不编译,并给出错误

lambdatemplate.cpp: In function ‘int main()’:
lambdatemplate.cpp:29:66: error: no matching function for call to ‘callthistemp(main()::__lambda3, int)’
     callthistemp<int>([](int x)->void{cout << "hello" << endl;},1); //(5)
                                                                  ^
lambdatemplate.cpp:29:66: note: candidate is:
lambdatemplate.cpp:17:6: note: template<class ... Args> void callthistemp(std::function<void(Args ...)>, Args&& ...)
 void callthistemp(function<void(Args...)> func, Args&&... args){
      ^
lambdatemplate.cpp:17:6: note:   template argument deduction/substitution failed:
lambdatemplate.cpp:29:66: note:   ‘main()::__lambda3’ is not derived from ‘std::function<void(Args ...)>’
     callthistemp<int>([](int x)->void{cout << "hello" << endl;},1); //(5)
Run Code Online (Sandbox Code Playgroud)

mmm*_*mmm 5

怎么样

template<typename L, typename... Args>
void callthistemp(L const &func, Args&&... args)
{
  func(std::forward<Args>(args)...);
}
Run Code Online (Sandbox Code Playgroud)

使用模板时,无需将lambda包装成(有时是昂贵的)std ::函数.(昂贵意味着它可能使用堆分配,在这种情况下不必要).