c++0x:通过引用接收 lambda 作为参数的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6458612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:11:17  来源:igfitidea点击:

c++0x: proper way to receive a lambda as parameter by reference

c++lambdac++11function-prototypesfunction-parameter

提问by lurscher

What is the right way to define a function that receives a int->intlambda parameter by reference?

定义int->int通过引用接收lambda 参数的函数的正确方法是什么?

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?

还有其他方法可以定义 lambda 参数吗?

回答by bdonlan

You cannot have an autoparameter. You basically have two options:

你不能有auto参数。你基本上有两个选择:

Option #1: Use std::functionas you have shown.

选项#1:std::function如您所示使用。

Option #2: Use a template parameter:

选项#2:使用模板参数:

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 fcan 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::functionobject.

在某些情况下,选项 #2 可能更有效,因为它可以避免为嵌入的 lambda 函数对象分配潜在的堆,但只有在f可以作为模板函数放置在标头中时才有可能。与任何模板一样,它还可能增加编译时间和 I-cache 占用空间。请注意,它也可能没有效果,就好像 lambda 函数对象足够小一样,它可以在std::function对象中内联表示。

回答by Nawaz

I would use templateas:

我会template用作:

template<typename Functor>
void f(Functor functor)
{
   cout << functor(10) << endl;
}

int g(int x)
{
    return x * x;
}
int main() 
{
    auto lambda = [] (int x) { cout << x * 50 << endl; return x * 100; };
    f(lambda); //pass lambda
    f(g);      //pass function 
}

Output:

输出:

500
1000
100

Demo : http://www.ideone.com/EayVq

演示:http: //www.ideone.com/EayVq

回答by Puddle

I know it's been 7 years, but here's a way nobody else mentioned:

我知道已经 7 年了,但这是其他人没有提到的一种方式:

void foo(void (*f)(int)){
    std::cout<<"foo"<<std::endl;
    f(1); // calls lambda which takes an int and returns void
}
int main(){
    foo([](int a){std::cout<<"lambda "<<a<<std::endl;});
}

Which outputs:

哪些输出:

foo
lambda 1

No need for templates or std::function

不需要模板或 std::function

回答by Reinstate Monica

void f(auto& lambda);

void f(auto& lambda);

That's close. What will actually compile is:

那很接近。实际编译的是:

#include <cassert>

/*constexpr optional*/ const auto f = [](auto &&lambda)
{
  lambda();
  lambda();
};

int main()
{
  int counter = 0;
  f([&]{ ++counter; });
  assert(counter == 2);
}