Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return variant from a lambda

I have this simple lambda:

    std::variant<int, char> myLambda = []() { // no suitable user-defined conversion from "type" to "std::variant<int, char>" exists
        std::variant<int, char> res;

        if (true)
        {
            res = 1;
        }
        else
        {
            res = 'c'; 
        }

        return res;
    };

But it doesn't compile, producing error no suitable user-defined conversion from "type" to "std::variant<int, char>" exists. What am I doing wrong?

like image 308
Nurbol Alpysbayev Avatar asked Jul 29 '26 00:07

Nurbol Alpysbayev


2 Answers

Either you mean

std::variant<int, char> v = []() {
    std::variant<int, char> res;

    if (true)
    {
        res = 1;
    }
    else
    {
        res = 'c'; 
    }

    return res;
}();
^^^

Or you mean

auto myLambda = []() {
    std::variant<int, char> res;

    if (true)
    {
        res = 1;
    }
    else
    {
        res = 'c'; 
    }

    return res;
};

Lambda expressions have unique types.

like image 200
Vlad from Moscow Avatar answered Jul 30 '26 15:07

Vlad from Moscow


The lambda expression type is wrong. You're trying to bind to std::variant<int, char>. Lambda expressions type name is impl-defined. Use auto:

auto processProjectFile = []() {
    std::variant<int, char> res;
    if (true) {
        res = 1;
    } else {
        res = 'c'; 
    }
    return res;
};

Optionally, you can cast the lambda type to std::function replacing auto by std::function<std::variant<int, char>(void)>.

But if you intend to call the lambda, just replace }; at the end by }();.

like image 33
João Paulo Avatar answered Jul 30 '26 15:07

João Paulo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!