问题
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