且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用模板将lambda转换为std ::函数

更新时间:2023-11-11 12:53:40

lambda函数对象作为类型 std :: function< T> 的参数,而不明确指定模板参数 T 。模板类型推导尝试将您的lambda函数的类型与 std :: function< T> 匹配,它在这种情况下不能做到 - 这些类型不是相同。模板类型扣除不考虑类型之间的转换。

You can't pass a lambda function object as an argument of type std::function<T> without explicitly specifying the template argument T. Template type deduction tries to match the type of your lambda function to the std::function<T> which it just can't do in this case - these types are not the same. Template type deduction doesn't consider conversions between types.

这是可能的,如果你可以给它一些其他方式来推断类型。你可以通过在 identity 类型中包装函数参数来做到这一点,以便在尝试匹配lambda到 std :: function时不会失败(因为依赖类型只是被类型扣除忽略)和一些其他参数。

It is possible if you can give it some other way to deduce the type. You can do this by wrapping the function argument in an identity type so that it doesn't fail on trying to match the lambda to std::function (because dependent types are just ignored by type deduction) and giving some other arguments.

template <typename T>
struct identity
{
  typedef T type;
};

template <typename... T>
void func(typename identity<std::function<void(T...)>>::type f, T... values) {
  f(values...);
}

int main() {
  func([](int x, int y, int z) { std::cout << (x*y*z) << std::endl; }, 3, 6, 8);
  return 0;
}

这在你的情况下显然没有用,因为你不想

This is obviously not useful in your situation though because you don't want to pass the values until later.

由于您不想指定模板参数,也不想传递可以推导出模板参数的其他参数,编译器将无法推导出您的 std :: function 参数的类型。

Since you don't want to specify the template parameters, nor do you want to pass other arguments from which the template parameters can be deduced, the compiler won't be able to deduce the type of your std::function argument.