Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make span of spans

C++20 std::span is a very nice interface to program against. But there doesn't seem to be an easy way to have a span of spans. Here's what I am trying to do:

#include <iostream>
#include <span>
#include <string>
#include <vector>

void print(std::span<std::span<wchar_t>> matrix) {
  for (auto const& str : matrix) {
    for (auto const ch : str) {
      std::wcout << ch;
    }
    std::wcout << '\n';
  }
}

int main() {
  std::vector<std::wstring> vec = {L"Cool", L"Cool", L"Cool"};
  print(vec);
}

This doesn't compile. How do I do something like that?

like image 303
Ayxan Haqverdili Avatar asked Jan 24 '26 01:01

Ayxan Haqverdili


1 Answers

Why not use a concept instead?

#include <iostream>
#include <string>
#include <vector>
#include <ranges>

template <class R, class T>
concept Matrix = 
    std::convertible_to<
        std::ranges::range_reference_t<std::ranges::range_reference_t<R>>,
        T>;

void print(Matrix<wchar_t> auto const& matrix) {
    for (auto const& str : matrix) {
        for (auto const ch : str) {
            std::wcout << ch;
        }
        std::wcout << '\n';
    }
}

int main() {
  std::vector<std::wstring> vec = {L"Cool", L"Cool", L"Cool"};
  print(vec);
}

godbolt.org

Thanks to Barry for suggesting the simplified concept above using the standard ranges library.

like image 145
Patrick Roberts Avatar answered Jan 25 '26 15:01

Patrick Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!