3

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?

kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39

2 Answers2

4

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_____|
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
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";
}
cigien
  • 57,834
  • 11
  • 73
  • 112