如何参数化用作另一个lambda的参数的lambda

时间:2018-08-28 06:01:12

标签: c++ lambda

#include <iostream>

// How to parameterize this lambda and use it in the second lambda?
auto print = []() { std::cout << "in print" << std::endl; };

auto repeat = [](auto function, const int num_repeat) {
  int ctr = 0;
  while (ctr++ < num_repeat) {
    function();
  }
};

int main() {
  repeat(print, 3);
  return 0;
}

在上述c ++示例中,我在另一个lambda print中使用了lambda函数repeat(不接受任何参数)作为参数。这适用于以下输出:

$ ./a.out 
in print
in print
in print

但是,我想将一个参数(或参数的可变列表)传递给print并在repeat中使用它。可能吗?例如,修改后的print如下所示:

auto print = [](std::string& name) { std::cout << "hello " << name << std::endl; };

2 个答案:

答案 0 :(得分:4)

我看不到问题吗?

#include <iostream>
#include <string>

// How to parameterize this lambda and use it in the second lambda?
auto print = []( const std::string& s ) { std::cout << s << std::endl; };

auto repeat = [](auto function, const int num_repeat) {
  int ctr = 0;
  while (ctr++ < num_repeat) {
    function( "call #" + std::to_string( ctr ) );
  }
};

int main() {
  repeat(print, 3);
}

您尝试过什么没有工作?

答案 1 :(得分:0)

这可能有帮助(来自cppreference

// generic lambda, operator() is a template with two parameters
auto glambda = [](auto a, auto&& b) { return a < b; };
bool b = glambda(3, 3.14); // ok

// generic lambda, operator() is a template with one parameter
auto vglambda = [](auto printer) {
    return [=](auto&&... ts) // generic lambda, ts is a parameter pack
    { 
        printer(std::forward<decltype(ts)>(ts)...);
        return [=] { printer(ts...); }; // nullary lambda (takes no parameters)
    };
};
auto p = vglambda([](auto v1, auto v2, auto v3) { std::cout << v1 << v2 << v3; });
auto q = p(1, 'a', 3.14); // outputs 1a3.14
q();                      // outputs 1a3.14