How to convert a lambda to an std::function using templates

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.

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.

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.

Leave a Comment