简体   繁体   English

带有lambdas作为参数的C ++函数

[英]C++ Functions with lambdas as arguments

I have an overload function, with the following signatures: 我有一个带有以下签名的重载函数:

void Foo(const std::function<void(int     )> &func);
void Foo(const std::function<void(int, int)> &func);

And when I want to use Foo() with lambdas, I'll have to do something like this: 当我想将Foo()与lambdas一起使用时,我将必须执行以下操作:

Foo((std::function<void(int     )>) [] (int i       ) { /* do something */ });
Foo((std::function<void(int, int)>) [] (int i, int j) { /* do something */ });

Both of which are not so user-friendly. 两者都不是那么用户友好。 It'd be a lot easier to use the function without having to add the casting "(std::function<...>)" before the lambdas - like this: 使用该函数要容易得多,而不必在lambda之前添加强制转换“(std :: function <...>)”,如下所示:

    Foo([] (int i       ) { /* do something */ }); // executes the 1st Foo()
    Foo([] (int i, int j) { /* do something */ }); // executes the 2nd Foo()

So, I need another overload, that accept lambda as its argument, and which automatically casts the lambda to one of the above signatures. 因此,我需要另一个重载,接受lambda作为其参数,并自动将lambda强制转换为上述签名之一。 How can this be done? 如何才能做到这一点? Or, is it possible in the first place? 或者,首先有可能吗?

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
}

Please help. 请帮忙。

PS. PS。 I'm using VS2010. 我正在使用VS2010。

If your lambda does not capture any variables—that is, it begins with [] —then it is convertible to a function pointer, and you can declare Foo like so: 如果您的lambda没有捕获任何变量(即,它以[]开头),那么它可以转换为函数指针,则可以这样声明Foo

void Foo(void(*func)(int));
void Foo(void(*func)(int, int));

If you want to keep the std::function versions, you can have these versions forward to that one. 如果要保留std::function版本,可以将这些版本转发到该版本。 If you don't want to implement them separately, I think a variadic template would do nicely: 如果您不想单独实现它们,我认为可变参数模板会很好地实现:

template<class... Args>
void Foo(void(*func)(Args...)) {
    return std::function<void(Args...)>(func);
}

If your lambdas capture variables, then they're not convertible to function pointers, and you'll need to wrap them in std::function yourself. 如果您的lambda捕获变量,则它们不能转换为函数指针,您需要自己将它们包装在std::function

Lambda's convert to std::function<> implicitly, there's no explicit conversion needed. Lambda隐式转换为std :: function <>,不需要显式转换。

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

Ah, you're trying to get a const reference to it. 嗯,您正在尝试获取const引用。 Why though? 为什么呢 You should be better off with a right-hand reference (as it's a temporary) or a copy. 最好使用右侧参考(因为这是临时参考)或副本。 In both of those cases it should implicitly convert as well... 在这两种情况下,它也应该隐式转换。

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

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