Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

no suitable user-defined conversion from "lambda []()-><error-type>" to "const std::vector<int, std::allocator<int>>"

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading