[英]Passing a lambda argument to a std::function parameter without intermediate variable
[英]Passing lambda as an argument to a function with std::function parameter with an arbitrary number of parameters
考虑下一个代码示例:
template <typename... TArgs>
void foo(std::function<void(TArgs...)> f) {
}
template <typename... TArgs>
class Class {
public:
static void foo(std::function<void(TArgs...)> f) {
}
};
为什么我可以这样做:
int main() {
// Helper class call
Class<int, int>::foo(
[](int a, int b) {}
);
}
但是我在这样做时遇到编译错误:
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) {
^
我只是想有一种方便的方式来使用诸如foo
之类的功能。
我试过这个:
std::function<void(int, int)> f = [](int a, int b) {
};
foo<int, int>(f); // ok
它奏效了。 这没关系。 但我想知道是否有任何方法可以在函数调用中直接使用 lambda,而无需创建本地函数对象。
当您调用foo<int, int>([](int a, int b) {});
, 包TArgs
仍然被推导以防需要扩展。 std::function<void(TArgs...)>
无法使用 lambda 参数为TArgs...
推导任何内容,因此它被推导为一个空包,这与给定的int, int
冲突。
对于Class<int, int>::foo
,没有模板参数推导,因为模板参数已经给出。
对此的解决方法是将其置于非推导上下文中:
template <typename... TArgs>
void foo(std::type_identity_t<std::function<void(TArgs...)>> f) {
}
或者根本不使用std::function
:
template <typename F>
void foo(F&& f) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.