When use a function template instead of a generic lambda?

↘锁芯ラ 提交于 2019-12-01 16:19:06

Function templates permit overloading of other functions with the same name, and calling them works via ADL. Generic lambdas are objects with an overloaded (), so neither works.

You can pass a function overload set to an object pretty easily:

 struct foo_overload_set_t {
   template<class...Ts>
   constexpr auto operator()(Ts&&...ts)const{ return foo(std::forward<Ts>(ts)...); }
 };

which with RVO can be optimized away completely (zero overhead), and an instance of the entire overload set can be passed to an algorithm. You can also do this with a lambda at point of use, which can be generated by a macro.

With a bit more boilerplate the above overload set can also support conversion to any call-compatible function pointer, which neither the template nor lambda solution supports (lambda requires signatures match one version, not compatibility).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!