在 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 astd::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 astd::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/