Constructing std::function argument from lambda

為{幸葍}努か 提交于 2019-11-28 13:55:37

Or can it be that for templates the automatic conversion does not take place at all?

Yes. Implicit conversions won't be considered in template argument deduction.

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

That means given MyFunction([](int){});, the implicit conversion (from lambda to std::function) won't be considered, then the deduction for TReturn and TArgs fails and the invocation attempt fails too.

As the workarounds, you can

  1. Use explicit conversion as you showed
  2. As the comment suggested, just use a single template parameter for functors. e.g.

    template<typename F>
    auto MyFunction2(F&& callback)
    {
         return [callback = std::move(callback)](auto&&... args)
         {
              return callback(std::forward<decltype(args)>(args)...);
         };
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!