简体   繁体   English

将lambda函数传递给其他方法

[英]Passing lambda functions to other methods

Do lambda function have a signature so that I can pass them around? lambda函数是否具有签名,以便我可以传递它们?

template<class Fn> 
HRESULT foreach(Fn _fuction)
{

}


object->foreach(
    [param1, param2] (int item) 
    {
    }
);

object->foreach(
    [param1, param2, param3] (int item) 
    {
    }
);

I want to use a typedef function instead of templates, I think the type of the function will strict the formal parameters but will allow captured list to vary. 我想使用typedef函数而不是模板,我认为函数的类型将严格限制正式参数,但允许捕获的列表变化。

can I use typedef instead of templates to pass lambda functions around? 我可以使用typedef而不是模板来传递lambda函数吗?

something like: 就像是:

typedef void (*Fn)(int);

but allows lambda not function pointer. 但允许lambda不能使用函数指针。

I tried using std::fuction but seems not working. 我尝试使用std :: fuction但似乎无法正常工作。

The type of the lambda-expression (which is also the type of the closure object) is a unique , unnamed non- union class type — called the closure type ... lambda表达式的类型(这也是闭包对象的类型)是唯一的 ,未命名的非联合类类型,称为闭包类型 ...

(C++11 §5.1.2/3, emphasis mine) (C ++ 11§5.1.2/ 3,重点是我的)

My reading of this is that even if two lambda-expressions have the same parameter list, return type, and capture list, they nevertheless have different types. 我的理解是,即使两个lambda表达式具有相同的参数列表,返回类型和捕获列表,它们仍然具有不同的类型。

auto f = []{};
typedef decltype(f) lambda_type;
void g(lambda_type lambda) { lambda(); }
int main() {
    g(f);    // OK
    g([]{}); // error: type mismatch
}

So no, what you are trying to do cannot be done. 因此,您尝试做的事情无法完成。 As others have suggested, try using std::function , or retain the template (what's wrong with templates, anyway?) 正如其他人建议的那样,请尝试使用std::function或保留模板(模板到底有什么问题?)

The actual type of a lambda is unspecified. 未指定lambda的实际类型。 But they are convertible to function ; 但是它们可以转换为function ; in your case, std::function<void(int)> ( void is the return type, the parameter types go in the parentheses). 在您的情况下,为std::function<void(int)>void是返回类型,参数类型放在括号中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM