Defaulting to user input using a lambda when parameter is not explicitly passed

泪湿孤枕 提交于 2020-05-29 09:34:58

问题


I wrote the following code (Still wondering about its uses...) to default to user input if the parameter is not passed.

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

unsigned getInput() {
    unsigned input;
    std::cin >> input;
    return input;
}

void foo(unsigned number = getInput()) {
    std::cout << number << "\n";
}

int main() {
    foo(1); //prints 1
    foo();  //defaults to user input    
    return 0;
}

What I wanted to ask was, is there any way we can convert the getInput() function to a lambda? Something on the lines of

void foo(unsigned number = { []() {unsigned num = 0; std::cin >> num; return num; } }) {
    std::cout << number << "\n";
}

Also, how does one achieve similar functionality in python?


回答1:


Yes, you can use a lambda. What you need to do is call the lambda after you define it like

void foo(unsigned number = []() {unsigned num = 0; std::cin >> num; return num; }()) 
//                         ^                   define lambda                    ^^^
//                                                               call lambda_____|



回答2:


Sure, but you are missing the call to the lambda:

void foo(unsigned number = [] {
               unsigned num = 0; 
               std::cin >> num; 
               return num; 
              }()   // <- call here
        ) 
{
    std::cout << number << "\n";
}


来源:https://stackoverflow.com/questions/61938875/defaulting-to-user-input-using-a-lambda-when-parameter-is-not-explicitly-passed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!