c++ - 如何将值传递给 lambda 函数

标签 c++ lambda

我正在尝试使用 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/

相关文章:

c++ - QLineWidget returnPressed 信号不工作

c++ - 如何组织游戏引擎

java - BiFunction 引用可以传递给需要功能接口(interface)的方法吗?

Java 8 流 : Map the same object multiple times based on different properties

c++ - 传递给模板函数的两个 lambda 使参数的类型推导不明确——为什么?

c# - 用于在 C# 中追加集合的 StringBuilder 扩展方法

c++ - 堆栈相关链表中的问题

c++ - wchar_t 字符串数组的成员丢失

c++ - 关于 C++ while 循环的语法混淆

kotlin - 如何在Kotlin中替换长链的forEach {}语句?