C++ C++;以lambdas作为参数的函数

C++ C++;以lambdas作为参数的函数,c++,lambda,C++,Lambda,我有一个重载函数,具有以下签名: void Foo(const std::function<void(int )> &func); void Foo(const std::function<void(int, int)> &func); 所以,我需要另一个重载,它接受lambda作为它的参数,并自动将lambda转换为上面的签名之一。如何做到这一点?或者,首先有可能吗 template <typename Function> void

我有一个重载函数,具有以下签名:

void Foo(const std::function<void(int     )> &func);
void Foo(const std::function<void(int, int)> &func);
所以,我需要另一个重载,它接受lambda作为它的参数,并自动将lambda转换为上面的签名之一。如何做到这一点?或者,首先有可能吗

template <typename Function> void Foo(Function function) {
    // insert code here: should be something like
    //   - check the signature of the 'function'; and
    //   - call 'Foo()' corresponding to the signature
}
模板无效Foo(函数){
//在此处插入代码:应类似于
//-检查“功能”的签名;以及
//-调用与签名对应的“Foo()”
}
请帮忙


另外,我正在使用VS2010。

如果lambda没有捕获任何变量,即,它以
[]
开头-然后它可以转换为函数指针,您可以这样声明
Foo

void Foo(void(*func)(int));
void Foo(void(*func)(int, int));
如果要保留
std::function
版本,可以将这些版本转发到该版本。如果您不想单独实现它们,我认为可变模板可以很好地实现:

template<class... Args>
void Foo(void(*func)(Args...)) {
    return std::function<void(Args...)>(func);
}
模板
void Foo(void(*func)(参数…){
返回std::函数(func);
}

如果lambda捕获变量,则它们不能转换为函数指针,您需要自己将它们包装在
std::function
中。

如果lambda没有捕获任何变量,即,它以
[]
开头,则它可以转换为函数指针,您可以这样声明
Foo

void Foo(void(*func)(int));
void Foo(void(*func)(int, int));
如果要保留
std::function
版本,可以将这些版本转发到该版本。如果您不想单独实现它们,我认为可变模板可以很好地实现:

template<class... Args>
void Foo(void(*func)(Args...)) {
    return std::function<void(Args...)>(func);
}
模板
void Foo(void(*func)(参数…){
返回std::函数(func);
}

如果Lambda捕获变量,那么它们不能转换为函数指针,您需要自己将它们封装在
std::function
中。

Lambda隐式转换为std::function,不需要显式转换

std::function<void(int, int)> func = [](int a, int b){ printf("Hello Lambda world!"); };
func(1, 2);
std::function func=[](inta,intb){printf(“Hello Lambda world!”);};
func(1,2);

啊,你是想得到一个常量引用。为什么呢?你最好有一个右手参考(因为它是临时的)或一份副本。在这两种情况下,它也应该隐式转换…

Lambda的convert to std::function隐式转换,不需要显式转换

std::function<void(int, int)> func = [](int a, int b){ printf("Hello Lambda world!"); };
func(1, 2);
std::function func=[](inta,intb){printf(“Hello Lambda world!”);};
func(1,2);

啊,你是想得到一个常量引用。为什么呢?你最好有一个右手参考(因为它是临时的)或一份副本。在这两种情况下,它也应该隐式转换…

您使用的编译器是什么,版本是什么?顺便说一句,在Clang3.3(Trunk177501)中运行良好。您使用的编译器是什么,版本是什么?顺便说一句,在Clang3.3(Trunk177501)中运行良好。对不起,我没有提到我使用的是VS2010,它不允许lambda进行函数指针转换。我想我将不得不改变我的编译器,或者继续使用它。。。非常感谢!抱歉,我没有提到我正在使用VS2010,它不允许lambda到函数指针转换。我想我将不得不改变我的编译器,或者继续使用它。。。非常感谢!