首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从lambda返回变量

从lambda返回变量
EN

Stack Overflow用户
提问于 2019-08-30 20:26:10
回答 2查看 200关注 0票数 3

我有一个简单的lambda:

代码语言:javascript
复制
    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;
    };

但是它不能编译,从而产生错误no suitable user-defined conversion from "type" to "std::variant<int, char>" exists。我做错了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-08-30 20:30:24

lambda表达式类型错误。您正在尝试绑定到std::variant<int, char>。Lambda表达式类型名称是impl定义的。使用auto

代码语言:javascript
复制
auto processProjectFile = []() {
    std::variant<int, char> res;
    if (true) {
        res = 1;
    } else {
        res = 'c'; 
    }
    return res;
};

或者,您可以将lambda类型强制转换为std::function,用std::function<std::variant<int, char>(void)>替换auto

但是,如果您打算调用lambda,只需将末尾的};替换为}();即可。

票数 6
EN

Stack Overflow用户

发布于 2019-08-30 20:34:26

你的意思是

代码语言:javascript
复制
std::variant<int, char> v = []() {
    std::variant<int, char> res;

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

    return res;
}();
^^^

或者你的意思是

代码语言:javascript
复制
auto myLambda = []() {
    std::variant<int, char> res;

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

    return res;
};

Lambda表达式具有独特的类型。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57726745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档