为什么我不能将 std::map 的条目解压缩到引用中?

Why can't I unpack entries of std::map into references?

我注意到从 std::map 解压键和值没有给我参考。我假设 std::map 中的各个条目存储为一对常量键和值。

什么有效:

什么不起作用:

为什么上面两个不行?附件是示例源代码,以及从 IDE 推导出的类型。编译器确实会在插入时产生相同的错误消息。

#include <map>
#include <type_traits>
#include <ranges>

int main() {
    std::map<int, int> data;

    for (const auto& kv : data) {
        auto& v = kv.second;
        auto& [a, b] = kv;
        static_assert(std::is_reference_v<decltype(v)>);
    }

    for (const auto& v : data | std::views::values)
        static_assert(std::is_reference_v<decltype(v)>);

    for (const auto& [k, v] : data)
        static_assert(std::is_reference_v<decltype(v)>);  // error

    {
        auto& kv = *data.begin();
        auto& [k, v] = kv;
        static_assert(std::is_reference_v<decltype(v)>);  // error
    }

    {
        auto kv = std::make_pair(3, 5);
        auto& k = kv.first;
        auto& v = kv.second;
        static_assert(std::is_reference_v<decltype(v)>);
    }

    return 0;
}

一个参考。但是,结构化绑定上的 decltype 有一个特殊规则(来自 [dcl.type.decltype]/1.1):

  • if E is an unparenthesized id-expression naming a structured binding ([dcl.struct.bind]), decltype(E) is the referenced type as given in the specification of the structured binding declaration;

并且映射对(pair<Key const, Value>)的 referenced 类型只是 Key constValue,从来没有任何类型参考。