当使用函数模板而不是通用lambda? [英] When use a function template instead of a generic lambda?

查看:149
本文介绍了当使用函数模板而不是通用lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以写一个函数模板:

I can write a function template:

template<typename T>
void f1(T parameter) { ... }

但在C ++ 14 ,我也可以创建一个通用的lambda:

But in C++14, I can also create a generic lambda:

auto f2 = [](auto parameter) { ... };

f1 c $ c> T 。在 f2 中,没有 T 可以引用,但是我可以使用 decltype

Within f1 I can refer to T directly. Within f2, there's no T to refer to, but I can get the same effect using decltype:

auto f2 = [](auto parameter)
          {
            using T = decltype(param);
            ...
          };

通用lambda的一个优点是我可以完全转发它。我不能这样与功能模板:

An advantage of the generic lambda is that I can perfect-forward it. I can't do that with the function template:

template<typename T>
void fwdToG(T&& param) { g(std::forward<T>(param)); }

fwdToG(f1);        // error!
fwdToG(f2);        // okay

有没有使用函数模板比​​使用通用lambda更好的情况? / p>

Are there situations where using a function template would be better than using a generic lambda?

推荐答案

函数模板 s允许重载同名的其他函数,并通过ADL调用它们的工作。通用lambdas是一个重载()的对象,因此无效。

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.

一个对象很容易:

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

,以及整个重载集合的实例可以传递给一个算法。您也可以在使用点处使用lambda来执行此操作,这可以由宏生成。

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.

有了更多样板,上述重载集也可以支持转换任何调用兼容函数指针,模板或lambda解决方案都不支持(lambda需要签名匹配一个版本,不兼容)。

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).

这篇关于当使用函数模板而不是通用lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆