我可以将std::map迭代器解包到可选的结构化绑定吗?

考虑以下代码:

#include<functional>
#include<iostream>
#include<map>

const std::map<int, std::string> numberToStr{{1, "one"}, {2,"two"}};
int main() {
    auto it = numberToStr.find(2);
    if (it ==numberToStr.end()){
        return 1;
    }
    const auto&[_, str] = *it;
    std::cout << str;
}

有什么方法可以让我解开it对 2 个可选项(_ 和 str)的潜在解引用,然后我可以写:

const auto&[_, str] = // some magic;
// _ is std::optional<int>, str is std::optional<str>
if (!str){
    return 1;
}
std::cout << *str;
}

我认为不是,因为结构化绑定是语言级别的东西,并且 std::optional 是一个库功能,并且 afaik 无法自定义交互。

注意:我想我可以实现我自己的映射,它返回知道它们是否指向 .end() 的迭代器,并“hack”自定义点以基于此执行可选逻辑,当我不控制时,我要求使用一般用例容器。

回答

您可以添加一个辅助函数,如

template <typename Key, typename Value, typename... Rest>
std::pair<std::optional<Key>, std::optional<Value>> my_find(const std::map<Key, Value, Rest...>& map, const Key& to_find)
{
    auto it = map.find(to_find);
    if (it == map.end())
        return {};
    else
        return {it->first, it->second};
}

然后你会像这样使用它

const auto&[_, str] = my_find(numberToStr, 2);
// _ is std::optional<int>, str is std::optional<str>
if (!str){
    return 1;
}
std::cout << *str;

如果你只关心这个值,你可以通过返回它来稍微缩短代码

template <typename Key, typename Value, typename... Rest>
std::optional<Value> my_find(const std::map<Key, Value, Rest...>& map, const Key& to_find)
{
    auto it = map.find(to_find);
    if (it == map.end())
        return {};
    else
        return {it->second};
}

然后你会像这样使用它

auto str = my_find(numberToStr, 2);
// str is std::optional<str>
if (!str){
    return 1;
}
std::cout << *str;


以上是我可以将std::map迭代器解包到可选的结构化绑定吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>