加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何使lambdas与std :: nullopt一起使用

发布时间:2020-12-16 09:20:55 所属栏目:百科 来源:网络整理
导读:背景 我有一系列lambda对捕获的变量执行不同的检查,如果检查失败则返回std :: nullopt. return std :: nullopt是第一个return语句.然后,如果检查成功,则继续并计算该值. 问题 返回表达式的类型不一致,例如std :: nullopt_t无法转换为std :: optional T,即使
背景

我有一系列lambda对捕获的变量执行不同的检查,如果检查失败则返回std :: nullopt. return std :: nullopt是第一个return语句.然后,如果检查成功,则继续并计算该值.

问题

返回表达式的类型不一致,例如std :: nullopt_t无法转换为std :: optional< T>,即使相反的方式有效.特别是,我想要下面的代码来编译和运行,打印2:

#include <functional>
#include <utility>
#include <optional>

int x = 3;

auto lambda = [](){
    if (x == 2)
        return std::nullopt;

    return std::optional(2);
};

#include <iostream>

int main () {
    using return_type = std::invoke_result_t<decltype(lambda)>;
    static_assert(std::is_same<return_type,std::optional<int>>{},"return type is still std::nullopt_t");

    std::cout << lambda().value() << 'n';
}

Wandbox Demo.

思考

我相信我需要使用std :: common_type< Args ...>在某个地方,但我既不能强制执行也不能推断Args,因为它可能需要语言支持.

解决方法

而不是使用模板类型推导来推断lambda的返回类型,为什么不明确指定返回类型?

auto lambda = []() -> std::optional<int> {
    if (x == 2)
        return std::nullopt;

    return 2;
};

std :: common_type通常是模板,你没有.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读