I try to implement lambda function:-
vector<int> numbers;
int value = 0;
cout << "Pushing back...\n";
while (value >= 0) {
cout << "Enter number: ";
cin >> value;
if (value >= 0)
numbers.push_back(value);
}
print( [numbers]() ->
{
cout << "Vector content: { ";
for (const int& num : numbers)
cout << num << " ";
cout << "}\n\n";
});
I got an error:-
1.Severity Code Description Project File Line Source Suppression State
Error (active) E0312 no suitable user-defined conversion from "lambda []()-><error-type>" to "const std::vector<int, std::allocator<int>>" exists consoleapplication C:\Users\insmitr\source\repos\consoleapplication\consoleapplication.cpp 46 IntelliSense
2.Severity Code Description Project File Line Source Suppression State
Error (active) E0079 expected a type specifier consoleapplication C:\Users\insmitr\source\repos\consoleapplication\consoleapplication.cpp 47 IntelliSense
Could you please help me in this regards
CodePudding user response:
The problem is that print
accepts a vector<int>
but while calling print
you're passing a lambda and since there is no implicit conversion from the lambda to the vector, you get the mentioned error.
You don't necessarily need to call print
as you can just call the lambda itself as shown below. Other way is to make print
a function template so that it can accept any callable and then call the passed callable.
int main()
{
std::vector<int> numbers;
int value = 0;
cout << "Pushing back...\n";
while (value >= 0) {
cout << "Enter number: ";
cin >> value;
if (value >= 0)
numbers.push_back(value);
}
//-------------------vvvv------>void added here
( [numbers]() -> void
{
cout << "Vector content: { ";
for (const int& num : numbers)
cout << num << " ";
cout << "}\n\n";
//----vv---->note the brackets for calling
})();
return 0;
}