我正在尝试使用 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)
没有必要让这个模式变得复杂。
关于c++ - 如何将值传递给 lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54254026/