如何使lambda与std::nullopt一起工作
How to make lambdas work with std::nullopt
Background
我有一系列 lambda 对捕获的变量执行不同的检查,如果检查失败,则返回std::nullopt
。return std::nullopt
是第一个返回语句。然后,如果检查成功,他们继续计算值。
问题
返回表达式的类型不一致,例如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';
}
魔杖盒演示。
思潮
我相信我需要在某处使用std::common_type<Args...>
,但我既不能强制存在它,也不能推断Args
,因为它可能需要语言支持。
与其使用模板类型推导来推断 lambda 的返回类型,为什么不显式指定该返回类型?
auto lambda = []() -> std::optional<int> {
if (x == 2)
return std::nullopt;
return 2;
};
std::common_type
通常使用模板,而您没有模板。
我建议坚持使用单个返回语句和显式指定的结果类型,而无需使用 nullopt。当函数返回整数或 nullopt 时,它看起来有些误导。特别是如果功能更长。此外,如果值类型是具有显式构造函数的东西,则使用emplace
可以避免再次键入值类型名称。
auto lambda = []()
{
std::optional<int> result{};
if(2 != x)
{
result.emplace(2);
}
return result;
};
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 如何使lambda与std::nullopt一起工作