首页 > 解决方案 > 从函数返回 std::array 作为范围

问题描述

假设我有两个数组:

constexpr std::array<int, 3> a1{1, 2, 3};

constexpr std::array<int, 5> a2{1, 2, 3, 4, 5};

将它们转换为相同类型的范围以使其可以process_result使用其返回值调用函数的正确方法是什么?

constexpr void process_result(RangeType range) { for (auto elem: range) { //do something with elem }

所以问题是什么RangeType

一个明显的解决方案是替换std::arraystd::vector,但我想知道该怎么做std::array

标签: c++c++20stdarray

解决方案


您可以使用 (non owning)std::span来允许任何连续的范围:

constexpr void process_result(std::span<const int> range)
{
    for (auto elem: range) {
        //do something with elem
    }
}

推荐阅读