[英]Passing lambda as an argument to a function with std::function parameter with an arbitrary number of parameters
Consider the next sample of the code:考虑下一个代码示例:
template <typename... TArgs>
void foo(std::function<void(TArgs...)> f) {
}
template <typename... TArgs>
class Class {
public:
static void foo(std::function<void(TArgs...)> f) {
}
};
Why can I do this:为什么我可以这样做:
int main() {
// Helper class call
Class<int, int>::foo(
[](int a, int b) {}
);
}
But I get a compile error doing this:但是我在这样做时遇到编译错误:
int main() {
// Function call
foo<int, int>(
[](int a, int b) {}
);
}
<source>:16:5: error: no matching function for call to 'foo'
foo<int, int>(
^~~~~~~~~~~~~
<source>:4:6: note: candidate template ignored: could not match
'std::function<void (int, int, TArgs...)>' against
'(lambda at <source>:17:9)'
void foo(std::function<void(TArgs...)> f) {
^
I just want to have a convenient way to use functions such as foo
.我只是想有一种方便的方式来使用诸如foo
之类的功能。
I've tried this:我试过这个:
std::function<void(int, int)> f = [](int a, int b) {
};
foo<int, int>(f); // ok
And it worked.它奏效了。 And this is ok.这没关系。 But I want to know if there is any way to use lambdas right in the function call, without creating a local function object.但我想知道是否有任何方法可以在函数调用中直接使用 lambda,而无需创建本地函数对象。
Because of this: Why is template parameter pack used in a function argument type as its template argument list not able to be explicit specified因为这个: Why is template parameter pack used in a function argument type as its template argument list not can be explicited specified
When you call foo<int, int>([](int a, int b) {});
当您调用foo<int, int>([](int a, int b) {});
, the pack TArgs
is still deduced in case it needs to be extended. , 包TArgs
仍然被推导以防需要扩展。 std::function<void(TArgs...)>
cannot deduce anything for TArgs...
with a lambda argument, so it gets deduced as an empty pack, which conflicts with the given int, int
. std::function<void(TArgs...)>
无法使用 lambda 参数为TArgs...
推导任何内容,因此它被推导为一个空包,这与给定的int, int
冲突。
For Class<int, int>::foo
, there is no template argument deduction since the template arguments are already given.对于Class<int, int>::foo
,没有模板参数推导,因为模板参数已经给出。
A fix for this is to put it in a non-deduced context:对此的解决方法是将其置于非推导上下文中:
template <typename... TArgs>
void foo(std::type_identity_t<std::function<void(TArgs...)>> f) {
}
Or don't take a std::function
at all:或者根本不使用std::function
:
template <typename F>
void foo(F&& f) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.