c++ - std::ranges::to 是否允许转换为 std::map?

标签 c++ std-ranges c++23

std::ranges::to 论文 wg21.link/p1206 中,概述部分具有以下内容

//Supports converting associative container to sequence containers
auto f = ranges::to<vector>(m);

但是我找不到在论文的其余部分中描述转换为 std::map 的细节的地方。我在 https://github.com/TartanLlama/ranges 中尝试了 range-v3 和 Sy Brand 的 ranges::to 实现。并且它们都不编译将范围转换为 std::map 的代码。那么这只是这些库中缺少的,还是正在转换为并非真正允许的 std::map

最佳答案

Does std::ranges::to allow converting to a std::map?

是的。

I tried range-v3 and Sy Brand's implementation of ranges::to in https://github.com/TartanLlama/ranges and neither of them compiles code converting a range to a std::map

我还没有尝试过 Sy 的实现,看起来 range-v3 的实现很奇怪:

#include <map>
#include <vector>
#include <range/v3/range/conversion.hpp>

int main() {
    std::vector<std::pair<int, int>> v = {{1, 2}, {3, 4}};

    // this works (explicit)
    // m1 is a std::map<int, int>
    auto m1 = ranges::to<std::map<int, int>>(v);

    // this works (deduced with a pipe)
    // m2 is a std::map<int, int>
    auto m2 = v | ranges::to<std::map>();

    // but this does not (deduced, direct call)
    auto m3 = ranges::to<std::map>(v);
}

问题是 range-v3 中的类模板直接调用版本出于某种原因专门尝试实例化 C<range_value_t<R>> (在这种情况下应该是 std::map<std::pair<int, int>>,显然是错误的)即使这里已经有一个元函数可以做正确的事情并且可以推断出 std::map<int, int>。 (由管道版本使用)。

ranges::to在标准库中指定这两个做同样(正确)的事情,所以这将在 C++23 中工作。这只是 range-v3 中的一个简单错误修复。

关于c++ - std::ranges::to 是否允许转换为 std::map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72082414/

相关文章:

c++ - 如何使用 GCC 12.1 生成 C++23 堆栈跟踪?

c++ - 在 C++ 中将函数传递给类

c++ - 从2个模板类继承 `sameFunctionName<T>()` ==>不明确

c++ - 为什么在 C++23 中分配_at_least()?

c++ - 使用 std::ranges::min 投影到 std::map

c++ - 组合范围适配器和 std::source_location 得到了奇怪的结果

c++ - C++23 中 default_constructible 范围适配器的含义是什么?

c++ - 不使用configure_file时如何使用CMake生成C++代码?

c++ - 变量模板的开销

c++ - 用户定义的容器不适用于 std::ranges