我正在嘗試實作一個find_if_opt幾乎相同的通用方法std::ranges::find_if(但它回傳一個可選的)
到目前為止,這是我的實作。
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:如果您對我的 range:: 包裝器有任何建議,而我仍然堅持使用 c 17,請隨意。
uj5u.com熱心網友回復:
您可以使用ranges::range_value_t獲得value_type的X
template <typename X, typename Z>
inline std::optional<std::ranges::range_value_t<X>>
find_if_opt(const X& ds, const Z& fn) {
const auto it = std::ranges::find_if(ds, fn);
if (it != end(ds)) {
return *it;
}
return {};
}
或使用std::iter_value_t獲取value_type迭代器
template <typename X, typename Z>
inline auto
find_if_opt(const X& ds, const Z& fn) {
const auto it = std::ranges::find_if(ds, fn);
if (it != end(ds)) {
return std::make_optional(*it);
}
return std::optional<std::iter_value_t<decltype(it)>>{};
}
或 C 20 之前的
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 std::optional<std::decay_t<decltype(*it)>>{};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/382476.html
