gpt4 book ai didi

c++ - 错误 : inconsistent types 'std::optional' and 'std::nullopt_t' deduced for lambda return type

转载 作者:行者123 更新时间:2023-12-03 23:33:31 27 4
gpt4 key购买 nike

auto operator  | (auto f1, auto f2) {
return [f1, f2]() {
if(f1) {
return f2(f1.value());
}
return std::nullopt;
};
}


int main() {
std::optional<int> a{11},b{};

auto z = a | [](auto b) -> std::optional<double>{
return b / 3.0;
};

auto x = z();
}
如何在运算符中使 lambda 返回类型通用|功能 ?
想法是实现运营商|它采用 optional 和 lambda ,仅当 optional 不是 nullopt 时才处理 lambda 并返回 lambda 返回类型的 optional

最佳答案

您可以使用 ? :

auto operator  | (auto f1, auto f2) {
return [f1, f2]() {
return f1?f2(f1.value()):std::nullopt;
};
}
因为它的类型组合规则没有自动返回类型推导那么严格。

关于c++ - 错误 : inconsistent types 'std::optional<double>' and 'std::nullopt_t' deduced for lambda return type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66081114/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com