c ++ 0x:通过引用接收lambda作为参数的正确方法 [英] c++0x: proper way to receive a lambda as parameter by reference
问题描述
通过引用定义接收 int-> int
lambda参数的函数的正确方法是什么?
void f(std :: function< int(int)&& lambda);
或
void f(auto& lambda);
我不确定最后一个表单是否是法律语法。
有其他方法来定义lambda参数吗?
不能有 auto
参数。您基本上有两个选项:
选项#1:使用 std :: function
p>
选项#2:使用模板参数:
template< typename F& ;
void f(F& lambda){/ * ... * /}
在某些情况下,选项#2可能更有效,因为它可以避免嵌入lambda函数对象的潜在堆分配,但只有在 f
作为模板函数。它也可以增加编译时间和I-cache足迹,如同任何模板一样。注意,它可能没有效果,如果lambda函数对象足够小,它可以在 std :: function
对象中内联表示。
What is the right way to define a function that receives a int->int
lambda parameter by reference?
void f(std::function< int(int) >& lambda);
or
void f(auto& lambda);
I'm not sure the last form is even legal syntax.
Are there other ways to define a lambda parameter?
You cannot have an auto
parameter. You basically have two options:
Option #1: Use std::function
as you have shown.
Option #2: Use a template parameter:
template<typename F>
void f(F &lambda) { /* ... */}
Option #2 may, in some cases, be more efficient, as it can avoid a potential heap allocation for the embedded lambda function object, but is only possible if f
can be placed in a header as a template function. It may also increase compile times and I-cache footprint, as can any template. Note that it may have no effect as well, as if the lambda function object is small enough it may be represented inline in the std::function
object.
这篇关于c ++ 0x:通过引用接收lambda作为参数的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!