Pavel Sh
Pavel Sh

Reputation: 79

Constructing an std::span<> from an std::ranges::forward_range?

I have the following function:

template <forward_range R>
void Merge(R src1, R src2, ostream& out);

But that only works for two containers of the same type. I need to create a wrapper for it to merge, e.g. an std::vector<int> and an std::list<int>, so my idea is to use an std::span as follows:

template <forward_range R1, forward_range R2>
void MergeSomething(R1&& src1, R2&& src2, ostream& out) {
    
    using T = std::ranges::range_value_t<R1>;
    
    std::span<T> src_span_1(src1);
    std::span<T> src_span_2(src2);
    
    Merge(src_span_1, src_span_2, out);
}

This compiles and works fine with two std::vectors:

    vector<int> v1{1, 3, 5};
    vector<int> v2{2, 4, 6};

    cout << "Merging vectors:"sv << endl;
    MergeSomething(v1, v2, cout);

But it doesn't compile for an std::vector<int> and std::list<int>, "no matching constructor for initialization of std::span<int>" error:

    vector<int> v1{60, 70, 80, 90};
    list<int> int_list{65, 75, 85, 95};

    cout << "Merging vector and list:"sv << endl;
    MergeSomething(v1, int_list, cout);

Let alone for containers with different value types (e.g. int and double). I tried changing the Merge and MergeSomething functions as follows, but there are multiple errors ("std::list does not provide a subscript operator" and "No matching constructor for initialization of std::span<int>")

template <forward_range R1, forward_range R2>
void Merge(R1 src1, R2 src2, ostream& out) {
 size_t i1 = 0, i2 = 0;
    while (i1 < src1.size() && i2 < src2.size()) {
        if (std::less{}(src1[i1], src2[i2])) {
          .
          /*do the merge...*/
          .
        }
    }
}

template <forward_range R1, forward_range R2>
void MergeSomething(R1&& src1, R2&& src2, ostream& out) {
    std::span<std::ranges::range_value_t<R1>> s1(src1);
    std::span<std::ranges::range_value_t<R2>> s2(src2);
    
    Merge(src1, src2, out);
}

Since the documentation on ranges is kind of sparse for now, can anyone clarify how to do this properly? Thnx!

Upvotes: 2

Views: 82

Answers (0)

Related Questions