【发布时间】:2022-01-18 20:36:18
【问题描述】:
我正在尝试实现一个通用的 find_if_opt 方法,它实际上与 std::ranges::find_if 相同(但是它返回一个 Optional)
到目前为止,这是我的实现。
template <typename X, typename Z>
inline auto find_if_opt(const X& ds, const Z& fn) {
const auto it = ranges::find_if(ds, fn);
if (it != end(ds)) {
return std::make_optional(*it);
}
return {};
}
auto test() {
std::vector v{1,2,3,4,5};
return ranges::find_if_opt(v, [](auto i){
return i == 2;
});
}
这是一个更大的 std::ranges 的一部分,比如 c++17 算法的包装器。请参阅https://godbolt.org/z/3fEe8bbh9(有关整个相关标头)
使用{}时编译器错误为:
<source>:29:16: error: cannot deduce return type from initializer list
return {};
^~
我也尝试过使用 std::nullopt,导致:
<source>:41:6: required from here
<source>:30:21: error: inconsistent deduction for auto return type: 'std::optional<int>' and then 'std::nullopt_t'
return std::nullopt;
^~~~~~~
PS:如果您对我的范围::包装器有任何建议,而我仍然坚持使用 c++17,请随时提出。
【问题讨论】:
-
nullopt不是std::optional,它是一种可用于默认构造std::optional的类型。返回std::optional<X>{}; -
使用
std::optional<X>{};不起作用,因为X是数据结构的类型,即X是std::vector<int>