1

Say I have two arrays:

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

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

What is the right way to convert them to ranges of the same type to make it possible to call process_result function with their return values?

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

So the question is what is RangeType.

An obvious solution is to replace std::array with std::vector, but I wonder to know what to do with std::array.

12
  • 3
    Can we see how process_result(RangeType range); is declared/defined? You might not need to do anything as an array is already a range. Commented Sep 13, 2021 at 13:09
  • @NathanOliver It has a parameter of RangeType and it is non-template. Commented Sep 13, 2021 at 13:13
  • @FrançoisAndrieux RangeType is what I am asking about. Commented Sep 13, 2021 at 13:17
  • 3
    std::span<const int>? Commented Sep 13, 2021 at 13:18
  • 1
    "An obvious solution is to replace std::array with std::vector". I don't see how it "defines" RangeType... Commented Sep 13, 2021 at 13:19

2 Answers 2

4

You might use (non owning) std::span to allow any contiguous ranges:

constexpr void process_result(std::span<const int> range)
{
    for (auto elem: range) {
        //do something with elem
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you don't necessarily need a function, and can instead use a function template, then you can make it more generic by supporting all ranges; not just contiguous ones:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.