【发布时间】:2020-05-03 18:29:50
【问题描述】:
我希望能够使用 C++ 范围通过压缩容器来帮助简化代码逻辑,而不是显式索引到它们中。我可以让它与一个冗长的 lambda 参数一起工作,但我宁愿尝试使用更多 auto 使其更简单/可概括。
const int n = ...;
std::vector<float> a(n), b(n), c(n);
...initialize a and b...
// This works
ranges::for_each(
ranges::views::zip(a, b, c),
[](const std::tuple<float&, float&, float&>& v)
{
const auto& [a, b, c] = v;
c = a + b;
std::cout << typeid(v).name(); // NSt3__15tupleIJRfS1_S1_EEE
}
);
// This fails
ranges::for_each(
ranges::views::zip(a, b, c),
[](const auto& v)
{
const auto& [a, b, c] = v;
// c = a + b;
std::cout << typeid(v).name(); // N6ranges12common_tupleIJRfS1_S1_EEE
}
);
Ranges-v3 文档说明如下:
views::zip给定 N 个范围,返回一个新范围,其中 Mth 元素是在所有 Mth 元素上调用
make_tuple的结果N 个范围。
这让我觉得应该可以把ranges::common_tuple转换成std::tuple,看了看公众号发现:
std::tuple< Ts... > const & base() const noexcept
但是这也不能编译:
const auto& [a, b, c] = v.base();
// error: no member named 'base' in 'std::__1::tuple<float, float, float>'
但是当我打印typeid(v) 时,它不是std::tuple;它是ranges::common_tuple。我在这里尝试使用auto 类型扣除可能吗? (clang 编译器,如果这很重要)
【问题讨论】:
-
在
[](const & v) { ... }中v的类型在哪里?尝试在那里添加auto作为类型。 -
糟糕,我打错了。应该是
[](const auto& v){ ... }导致ranges::common_tuple
标签: c++ tuples c++17 auto structured-bindings