如何将值传递给 lambda 函数

How to pass value to lambda function

本文关键字:lambda 函数 值传      更新时间:2023-10-16

我正在尝试使用 lambda 在我的函数参数中组合多个步骤。我试过:

void testLambda(const char* input, const char* output = [](const char* word){return word;}(input)){
     std::cout << input << " " << output << std::endl;
}

这个函数应该:如果

testLambda("hallo");

被调用,从第一个参数中取出并创建第二个参数(默认)并打印hallo hallo .我怎样才能做到这一点?

你不能这样做——默认参数不够复杂。即使它们是,这也不是非常清晰的代码。

只需写一个重载!

void testLambda(const char* input, const char* output)
{
     std::cout << input << ' ' << output << 'n';
}
void testLambda(const char* input)
{
    return testLambda(input, input);
}

或者,如果您不想这样做:

void testLambda(const char* input, const char* output = nullptr)
{
     std::cout << input << ' ' << (output ? output : input) << 'n';
}

(然后重命名函数:P)

没有必要使这种模式变得复杂。